swift如何从远程保护下载 json 文件并保存为脱机访问捆绑

标签: json Swift
发布时间: 2017/3/1 0:02:02
注意事项: 本文中文内容可能为机器翻译,如要查看英文原文请点击上面连接.

我能够从服务器下载一个 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
    })
}

}

解决方法 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
}
赞助商