2016-10-25 31 views
1

在下面的代碼中,我試圖寫入我在我的項目中的xcode文件。但對於某些問題,它不寫信給它。我在我的文件沒有得到更新文本(JSON文件)Swift3不寫入文件

 responseString = "Some Text"   
     if let path = Bundle.main.path(forResource: "mapsdatademo", ofType: "json") { 
      do{ 
       try responseString.write(toFile: path, atomically: false, encoding: String.Encoding.utf8) 
      }catch {"Error writting data"} 
     } 

我能夠讀取該文件。

if let path = Bundle.main.path(forResource: "mapsdatademo", ofType: "json") { 
     do { 
      let data = try Data(contentsOf: URL(fileURLWithPath: path), options: .alwaysMapped)} 

注:我試圖得到得到JSON數據,並編寫成一份文件。

+1

的可能的複製[如何保存一個數組中的應用在迅速mainBundle到的.plist(http://stackoverflow.com/questions/26889507/how-to-save-an-array-to- plist-in-the-apps-mainbundle-in-swift) – rmaddy

回答

-2

你的問題是responseString.write(TOFILE :)

responseString = "Some Text" 
do { 
     try self. responseString.write(to: path!, atomically: true, encoding: String.Encoding.utf8) 
}catch{ 
      print(error) 
} 
+1

不,這不是問題的原因。 – rmaddy

1

的iOS是沙箱。您可以從包中讀取,但不能寫入。寫入文檔目錄。

if var path = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first { 
    path = path.appendingPathComponent("mapsdatademo.json") 
    do{ 
     try responseString.write(toFile: path, atomically: false, encoding: String.Encoding.utf8) 
    }catch {"Error writting data"} 
}