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

cs7cruho  于 2023-04-13  发布在  Swift
关注(0)|答案(3)|浏览(239)

我正在将NSData示例的内容写入文件。我目前正在使用XcodePlayground。
这是我的代码:

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的文件,但当我检查它时,里面什么都没有。我也尝试删除并查看是否会创建该文件,但仍然不起作用。

ig9co6j1

ig9co6j11#

使用以下分机:

extension Data {

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

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

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

        return url
    }
}
eivnm1vs

eivnm1vs2#

您的代码正确,但未将文件写入您预期的位置。Swift Playgrounds是沙盒,文件位于系统的另一部分,而不是您项目的resources文件夹中。
您可以通过立即尝试读取文件来检查该文件是否确实被保存,如下所示:

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
    }
}

下面是Tom的评论:具体地说,文件位于像/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.这样的位置

vulvrdjw

vulvrdjw3#

  • 更新了答案,因为使用“文档”文件夹的旧方法不再起作用:*

因为你使用的是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)")
}

现在目录已经存在,您可以在那里读写数据了

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

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

do {
    try greeting.write(to: testFile, atomically: true, encoding: .utf8)
} catch {
    print("Write error: \(error)")
}

相关问题