2016-08-17 30 views
2

我正在努力獲取寫入文件的NSData實例的內容。我目前正在使用Xcode操場。如何在Swift中將NSData寫入新文件?

這是我的代碼:

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但是當我檢查它裏面有什麼。我也嘗試刪除,看看文件是否會被創建,但它仍然不起作用。

+1

你嘗試處理錯誤?有錯誤嗎? – jtbandes

回答

1

您的代碼是正確的,但該文件未被寫入您期望的位置。斯威夫特遊樂場是沙盒,文件是在系統的另一部分,而不是在你的項目的資源文件夾。

您可以檢查該文件實際上被保存通過立即試圖從中讀取,像這樣:

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

具體而言,該文件位於'/private/var/folders/bc/lgy7c6tj6pjb6cx0p108v7cc0000gp/T/com.apple.dt.Xcode.pg/containers/com.apple.dt.playground.stub.iOS_Simulator.MyPlayground- 105DE0AC-D5EF-46C7-B4F7-B33D8648FD50/newdata.json'。 OS X沙盒會讓它在其他地方寫入變得很尷尬。 –

+0

將此項添加到可見性答案中,謝謝!這是一個超長的路徑.. – Carter

+0

我發現在Xcode 8中有一個新的方法。請參閱我的答案。 –

1

如果您使用Xcode 8,還有更好的方法。

首先,在您的Documents文件夾中創建一個名爲Shared Playground Data的目錄。

接下來,在你的操場進口操場支持:

import PlaygroundSupport 

最後,用在你的文件URL playgroundSharedDataDirectory。這將指向上面創建的文件夾:

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

然後,您可以讀/寫URL在操場上,和(更容易)檢查您所保存的文件。這些文件將位於您在上面創建的Shared Playground Data文件夾中。

1

使用以下擴展名:

extension Data { 

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

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

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

     return url 
    } 
}