什么是离线存储数据并在应用程序上线时更新数据的最佳方式

时间:2017-11-20 06:11:44

标签: ios swift xcode

我正在尝试使用NSUserDefaults但是当我将应用程序离线时无法显示数据。

 let params: [String: String] = ["user-login-key" : loginkey , "api-key" : "ebaa3e8571444005cc0b609824e90dc8"]

    Alamofire.request("http://34.210.142.70/isdental/api/v2.0/home/featured", method: .get, parameters: nil, encoding: URLEncoding.default, headers: params).responseJSON { (response:DataResponse<Any>) in

        switch(response.result) {
        case .success(_):
            if let data = response.result.value{
                let json1 = data as! NSDictionary

                UserDefaults.standard.set(NSKeyedArchiver.archivedData(withRootObject: json1), forKey: "JsonFeatured")

                let jsond = UserDefaults.standard.object(forKey: "JsonFeatured") as? NSData

                let  json = NSKeyedUnarchiver.unarchiveObject(with: jsond! as Data) as! NSDictionary

                self.CollectionArray = json.object(forKey: "banners") as! NSArray
          }

1 个答案:

答案 0 :(得分:1)

  • 您没有检查失败情况。
  • 如果您离线,Alamofire会遇到失败案件。

检查以下代码会对您有所帮助。

        case .success(_):
            if let data = response.result.value{
                let json1 = data as! NSDictionary
                UserDefaults.standard.set(NSKeyedArchiver.archivedData(withRootObject: json1), forKey: "JsonFeatured")

                let jsond = UserDefaults.standard.object(forKey: "JsonFeatured") as? NSData

                let  json = NSKeyedUnarchiver.unarchiveObject(with: jsond! as Data) as! NSDictionary

              //self.CollectionArray = json.object(forKey: "banners") as! NSArray
            }

        case .failure(_):
            if (UserDefaults.standard.object(forKey: "JsonFeatured") != nil){
                if let savedData = NSKeyedUnarchiver.unarchiveObject(with: UserDefaults.standard.object(forKey: "JsonFeatured") as! Data)
                {
                    let  json = NSKeyedUnarchiver.unarchiveObject(with: savedData as! Data) as! NSDictionary

                    self.CollectionArray = json.object(forKey: "banners") as! NSArray

                }
            }
            break

        }