我正在尝试使用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
}
答案 0 :(得分:1)
检查以下代码会对您有所帮助。
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
}