2017-04-27 104 views
-1

我正在使用SwiftyJSON來讀取API響應。如何存儲JSON響應並保存到JSON文件

我想通過創建JSON文件離線在用戶設備本地存儲JSON響應。

我的函數返回創建JSON:現在

Alamofire.request(HostURL) 
     .responseJSON { response in 
      guard response.result.isSuccess else { 
       debugPrint("getCourseDataFromCourseId: Error while fetching tags \(String(describing: response.result.error))") 
       failure(response.result.error! as NSError) 
       return 
      } 

      guard response.result.error == nil else { 
       debugPrint(response.result.error!) 
       return 
      } 

      guard let json = response.result.value else { 
       debugPrint("JSON Nil") 
       return 
      } 

      let swiftJson = JSON(json) 
+0

告訴我們你試過的東西 –

+0

我已經添加了我的代碼。 –

回答

3

然後你只需要得到從JSON數據,然後使用Datawrite(to:)方法來存儲DocumentDirectory

if let data = try? json.rawData() { 
    let fileUrl = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0] 
        .appendingPathComponent("Sample.json") // Your json file name 
    try? data.write(to: fileUrl) 
} 

JSON響應編輯:現在後來,當你想從這個文件中讀取JSON訪問它的方式。

if let data = try? Data(contentsOf: fileURL) { 
    let json = JSON(data: data) 
} 
+0

但是如何從保存的文件中再次讀取。 –

+0

是的,但這次文件將在設備存儲中。不在項目中。 –

+0

好的確定了謝謝你 –