如何快速保存文件中的数据并使用UserDefault加载

时间:2017-03-24 07:01:32

标签: ios swift nsuserdefaults

我已经从JSON API获得了数据。所以我想保存数据配置文件然后加载,如果我想使用它。

这是我的代码解析json

let task = session.dataTask(with: request as URLRequest, completionHandler: { data, response, error in
               guard error == nil else {
                    return
                }

                guard let data = data else {
                    return
                }

                do {
                    //create json object from data
                    if let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String: Any] {
                        print(json)
                        // handle json...



                        }

                        DispatchQueue.main.async(
                            execute:self.LoginDone
                        )
                    }

                } catch let error {
                    print(error.localizedDescription)
                }
            })
            task.resume()

in

  

打印(JSON)

我将获得像Name,Addres等数据配置文件。所以,我将保存然后加载 但我想用另一个文件保存它。

1 个答案:

答案 0 :(得分:1)

让我们创建一个用户对象,遵守NSCoding协议并实现decodeencode函数,如下所示:

class User: NSObject, NSCoding {

    var name: String!
    var address: String!

    init(name: String, address: String) {
        self.name = name
        self.address = address
    }

    func encode(with aCoder: NSCoder) {
        if let name = name {
            aCoder.encode(name, forKey: "name")
        }
        if let address = address {
            aCoder.encode(address, forKey: "address")
        }
    }

    required init?(coder aDecoder: NSCoder) {
        if aDecoder.containsValue(forKey: "name") {
            self.name = aDecoder.decodeObject(forKey: "name") as! String
        }
        if aDecoder.containsValue(forKey: "address") {
            self.address = aDecoder.decodeObject(forKey: "address") as! String
        }
    }
}

现在,您可以保存并检索用户:

let user = User(name: "Danh", address: "1234 XYZ st")

// save user
let data = NSKeyedArchiver.archivedData(withRootObject: user)
UserDefaults.standard.set(data, forKey: "user")

// retrieve user
if let data = UserDefaults.standard.value(forKey: "user") as? Data,
    let user = NSKeyedUnarchiver.unarchiveObject(with: data) as? User {
    print("name: \(user.name), address: \(user.address)")
}