如何在 Swift 中将 NSData 写入新文件?

问题描述 投票:0回答:3

我正在努力将 NSData 实例的内容写入文件。我目前正在使用 Xcode 游乐场。

这是我的代码:

let validDictionary = [
    "numericalValue": 1,
    "stringValue": "JSON",
    "arrayValue": [0, 1, 2, 3, 4, 5]
]

let rawData: NSData!


if NSJSONSerialization.isValidJSONObject(validDictionary) {
    do {
        rawData = try NSJSONSerialization.dataWithJSONObject(validDictionary, options: .PrettyPrinted)
        try rawData.writeToFile("newdata.json", options: .DataWritingAtomic)
    } catch {
        // Handle Error
    }
}

我在资源中有一个名为 newdata.json 的文件,但当我检查它时,里面什么也没有。我也尝试删除并查看是否会创建该文件,但它仍然不起作用。

ios json swift xcode nsdate
3个回答
6
投票

使用以下扩展名:

extension Data {

    func write(withName name: String) -> URL {

        let url = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(name)

        try! write(to: url, options: .atomicWrite)

        return url
    }
}

2
投票

你的代码是正确的,但文件没有写在你期望的地方。 Swift Playgrounds 是沙盒化的,文件位于系统的另一部分,而不是项目的资源文件夹中。

您可以通过立即尝试读取文件来检查文件是否确实被保存,如下所示:

let validDictionary = [
    "numericalValue": 1,
    "stringValue": "JSON",
    "arrayValue": [0, 1, 2, 3, 4, 5]
]

let rawData: NSData!


if NSJSONSerialization.isValidJSONObject(validDictionary) { // True
    do {
        rawData = try NSJSONSerialization.dataWithJSONObject(validDictionary, options: .PrettyPrinted)
        try rawData.writeToFile("newdata.json", options: .DataWritingAtomic)

        var jsonData = NSData(contentsOfFile: "newdata.json")
        var jsonDict = try NSJSONSerialization.JSONObjectWithData(jsonData!, options: .MutableContainers)
        // -> ["stringValue": "JSON", "arrayValue": [0, 1, 2, 3, 4, 5], "numericalValue": 1]

    } catch {
        // Handle Error
    }
}

来自汤姆下面的评论:具体来说,文件在某个地方,比如

/private/var/folder‌​s/bc/lgy7c6tj6pjb6cx0‌​p108v7cc0000gp/T/com.‌​apple.dt.Xcode.pg/con‌​tainers/com.apple.dt.‌​playground.stub.iOS_S‌​imulator.MyPlayground‌​-105DE0AC-D5EF-46C7-B‌​4F7-B33D8648FD50/newd‌​ata.json.


1
投票

更新的答案,因为使用“文档”文件夹的旧方法不再有效:

由于您使用的是 Xcode playgrounds,因此可以使用共享的 playground 数据位置。您可以找到我导入的

PlaygroundSupport
然后使用它定义的
playgroundSharedDataDirectory
URL:

import PlaygroundSupport

print("Shared location: \(playgroundSharedDataDirectory)")

这提供了一个目录位置,您可以在 playgrounds 中使用,但是这个目录在您创建它之前不存在。在使用它之前,做这样的事情:

do {
    if !FileManager.default.fileExists(atPath: playgroundSharedDataDirectory.path) {
        try FileManager.default.createDirectory(at: playgroundSharedDataDirectory, withIntermediateDirectories: false)
    }
} catch {
    print("FileManager error: \(error)")
}

现在该目录已经存在,您可以在那里读写数据。使用共享目录中的文件 URL,例如

let testFile = playgroundSharedDataDirectory.appendingPathComponent("test.txt")

然后像使用任何普通文件 URL 一样使用它,例如:

do {
    try greeting.write(to: testFile, atomically: true, encoding: .utf8)
} catch {
    print("Write error: \(error)")
}
© www.soinside.com 2019 - 2024. All rights reserved.