json - 单击保存按钮时如何更改存储的 JSON 数据? swift 3

标签 json swift swift3 nsuserdefaults

我在登录时将我的用户 JSON 数据存储在“用户”上。单击保存按钮时如何更改值?例如:crew_preferred_name 到“Xiao Pang”。

UserDefaults.standard.set(json, forKey: "json")
user = UserDefaults().value(forKey: "json")as? NSDictionary

这是 JSON 输出

}
crew ={
"crew_avatar" = "http://ec2-52-221-231-3.ap-southeast-1.compute.amazonaws.com/gv/images/profile_image/Pang_Kang_Ming_916210_0e9.jpg";
"crew_contact" = 0123456789;
"crew_email" = "pang@xover.com.my";
"crew_gender" = Male;
"crew_id" = PP000001;
"crew_name" = "Pang Kang Ming";
"crew_preferred_name" = PKM;
"crew_qrcode" = "images/qrcode/qrcode_085960293a5378a64bec6ebfa3c89bb7.png";  }   

message = "Login Sucessfully";
result = success;
}

这是按钮代码,我将操作发布到 php,但不知道如何更改或保存“用户”数据中的更改。如果没有代码,我必须重新登录才能看到新的更新。

@IBAction func saveBtn(_ sender: Any) {
    let preferName = preferNameEditLabel.text!;

    if let crew = user!["crew"] as? [String:Any], let crewID = crew["crew_id"] as? String, let crewEmail = crew["crew_email"] as? String, let crewContact = crew["crew_contact"] as? String {

        let param = ["action": "update profile", "crew": ["crew_id": crewID, "crew_preferred_name": preferName, "crew_email": crewEmail, "crew_contact": crewContact]] as [String : Any]

        let headers = [
            "content-type": "application/json",
            "cache-control": "no-cache"
        ]

        if let postData = (try? JSONSerialization.data(withJSONObject: param, options: [])) {

            let request = NSMutableURLRequest(url: URL(string: "http://52.221.231.3/gv/app_api.php")!,
                                              cachePolicy: .useProtocolCachePolicy,
                                              timeoutInterval: 10.0)
            request.httpMethod = "POST"
            request.allHTTPHeaderFields = headers
            request.httpBody = postData

            _ = URLSession.shared

            if preferNameEditLabel.text != ""{
                let task = URLSession.shared.dataTask(with: request as URLRequest) {
                    (data, response, error) -> Void in
                    DispatchQueue.main.async(execute: {
                        if let json = (try? JSONSerialization.jsonObject(with: data!, options: [.mutableContainers])) as? NSDictionary
                        {
                            let result = json["result"] as? String

                            if (result == "success") {
                                print(result!)

                                self.view.endEditing(true)

                                let alert = UIAlertController(title: "Updated", message: "Update Successfully", preferredStyle: UIAlertControllerStyle.alert)
                                let okButton = UIAlertAction(title: "OK", style: UIAlertActionStyle.cancel, handler: nil)
                                alert.addAction(okButton)
                                self.present(alert, animated: true, completion: nil)

                            }else{
                                let alert = UIAlertController(title: "Error", message: "Update Failed", preferredStyle: UIAlertControllerStyle.alert)
                                let okButton = UIAlertAction(title: "OK", style: UIAlertActionStyle.cancel, handler: nil)
                                alert.addAction(okButton)
                                self.present(alert, animated: true, completion: nil)
                                print(result!)
                            }
                        }
                    })
                }

                task.resume()

            }else{
                let alert = UIAlertController(title: "Error", message: "Empty!", preferredStyle: UIAlertControllerStyle.alert)
                let okButton = UIAlertAction(title: "OK", style: UIAlertActionStyle.cancel, handler: nil)
                alert.addAction(okButton)
                self.present(alert, animated: true, completion: nil)
            }

        }

    }

}

最佳答案

不要在 Swift 中使用 NSDictionary,使用它的原生 Swift 对应物,Dictionary

然后您可以像这样访问和更改与已知键关联的值(您需要确保 json 的类型是 [String:Any]在将其保存到 UserDefaults 以使此代码正常工作之前):

UserDefaults.standard.set(json, forKey: "json")
user = UserDefaults().value(forKey: "json") as! [String:Any]
user["crew_name] = "Pang Kang Feng"

关于json - 单击保存按钮时如何更改存储的 JSON 数据? swift 3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45794517/

相关文章:

ios - Swift 如何更改 withBlock 语句中的外部对象值

swift - 向协议(protocol)变量添加两个约束

javascript - 验证在 JavaScript 中设置为 JSON 的电子邮件扩展列表

ruby-on-rails - 如何使用 Ruby 将 JSON 时间字符串自动转换为时间对象?

javascript - 以 JSON 格式返回 HTML 并调用函数

php - php和mysql数据库与android的连接

ios - 在 Swift-Json 中创建 NSMutableDictionary

iphone - 当选择文本字段时将 View 移到键盘后面

arrays - Swift 3 - 从字典数组中获取值

swift - 将时间转换函数更改为 Swift 扩展