2017-01-16 43 views
1

我可以從服務器下載json文件,並在每次打開應用程序時將其放入TableView中。 (請參閱下面的代碼)如何從遠程保存程序下載json文件並保存爲離線訪問包

但是,我還希望允許使用上次下載的文件進行脫機訪問。所以基本上我無法解決如何保存下載的文件進行本地訪問離線。任何幫助(尤其是例子)非常感謝。

class KalkanTableController: UITableViewController { 

var TableData:Array<String> = Array <String>() 


override func viewDidLoad() { 
super.viewDidLoad() 


get_data_from_url("http://ftp.MY FILE LOCATION/kalkanInfoTest.json") 
    if let path = Bundle.main.path(forResource: "kalkanInfoTest", ofType: "json") { 
     do { 
      let jsonData = try NSData(contentsOfFile: path, options: NSData.ReadingOptions.mappedIfSafe) 
      do { 
       let jsonResult: NSDictionary = try JSONSerialization.jsonObject(with: jsonData as Data, options: JSONSerialization.ReadingOptions.mutableContainers) as! NSDictionary 
      } catch {} 
     } catch {} 
    } 
} 


override func numberOfSections(in tableView: UITableView) -> Int { 
    return 1 
} 

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
    return TableData.count 
} 

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) 

    cell.textLabel?.text = TableData[indexPath.row] 
    return cell 
} 

func get_data_from_url(_ link:String) 
{ 
    let url:URL = URL(string: link)! 
    let session = URLSession.shared 

    let request = NSMutableURLRequest(url: url) 
    request.httpMethod = "GET" 
    request.cachePolicy = URLRequest.CachePolicy.reloadIgnoringCacheData 


    let task = session.dataTask(with: request as URLRequest, completionHandler: { 
     (
     data, response, error) in 

     guard let _:Data = data, let _:URLResponse = response , error == nil else { 

      return 
     } 
     self.extract_json(data!) 
    }) 
    task.resume() 
} 


func extract_json(_ data: Data) 
{ 
    let json: Any? 
    do 
    { 
     json = try JSONSerialization.jsonObject(with: data, options: []) 
    } 
    catch 
    { 
     return 
    } 

    guard let data_list = json as? NSArray else 
    { 
     return 
    } 

    if let item_list = json as? NSArray 
    { 
     for i in 0 ..< data_list.count 
     { 
      if let item_obj = item_list[i] as? NSDictionary 
      { 
       if let item_name = item_obj["kalkanInfo"] as? Stri       
        { 
         TableData.append(item_name) 

         print(item_name) 
       } 
      } 
     } 
    } 
    DispatchQueue.main.async(execute: {self.do_table_refresh()}) 
} 

func do_table_refresh() 
{ 
    DispatchQueue.main.async(execute: { 
     self.tableView.reloadData() 
     return 
    }) 
} 

}

+0

我不知道在這裏你的問題...但你可以閱讀更多關於__ [iOS上的數據存儲](https://developer.apple.com/icloud/documentation/data-storage/index.html)__。 – holex

回答

1

你可以嘗試保存您的JSON本地使用這些方法,以節省磁盤

override func viewDidLoad() { 
    super.viewDidLoad() 

    if readKalkanDataFromDisk() { 
     extract_json(readKalkanDataFromDisk()) 
    } else { 
     get_data_from_url("http://ftp.MY FILE LOCATION/kalkanInfoTest.json") 
    } 
} 

func get_data_from_url(_ link:String) 
{ 
    let url:URL = URL(string: link)! 
    let session = URLSession.shared 

    let request = NSMutableURLRequest(url: url) 
    request.httpMethod = "GET" 
    request.cachePolicy = URLRequest.CachePolicy.reloadIgnoringCacheData 


    let task = session.dataTask(with: request as URLRequest, completionHandler: { 
     (
     data, response, error) in 

     guard let _:Data = data, let _:URLResponse = response , error == nil else { 

      return 
     } 
     saveKalkanDataOnDisk(kalkanData: data!) 
     self.extract_json(data!) 
    }) 
    task.resume() 
} 

func saveKalkanDataOnDisk(kalkanData: Data) { 
    do { 
     let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first! 
     let fileURL = documentsURL.appendingPathComponent("Kalkan.json") 
     try kalkanData.write(to: fileURL, options: .atomic) 
    } catch { } 
} 

func readKalkanDataFromDisk() -> Data? { 
    let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first! 
    let filePath = documentsURL.appendingPathComponent("Kalkan.json").path 
    if FileManager.default.fileExists(atPath: filePath), let data = FileManager.default.contents(atPath: filePath) { 
     return data 
    } 
    return nil 
} 
+0

嗨拉蒙。感謝您花時間發佈。我不確定我將如何調用函數或從何處調用它們?你能照亮我嗎?最好的祝願 – PhilipS

+0

當你從url獲得你的json並在viewDidLoad上調用readData來查看你是否有磁盤上的數據或者你是否必須從網上下載它時,你可以在你的任務完成處理程序中調用saveData。 –

+0

@RamonVasconceolos 對不起,我很厚。能給我看看麼? – PhilipS