【问题标题】:How to change stored JSON data when i clicked save button? swift 3单击保存按钮时如何更改存储的 JSON 数据?迅速 3
【发布时间】:2017-08-21 10:12:13
【问题描述】:

我在登录时将我的用户 JSON 数据存储在“用户”上。当我点击保存按钮时如何更改值?类似于:crew_preferred_name to "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)
            }

        }

    }

}

【问题讨论】:

  • 只需在 UserDefaults 中针对同一个键保存新值。
  • @UmairAfzal 这个代码? UserDefaults.standard.set(json, forKey: "json") user = UserDefaults().value(forKey: "json") as? NSDictionary

标签: json swift swift3 nsuserdefaults


【解决方案1】:

不要在 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 数据?
  • 其实是user = UserDefaults.standard.object(forKey: "json") as! [String:Any]。请不要采用 value(forKey 之类的不良语法
【解决方案2】:

获取最新数据后直接写这一行

UserDefaults.standard.set(json, forKey: "json")

这样你的“json”键将包含最新的数据,你可以得到它

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

【讨论】:

  • 我试过了,但代码删除了所有数据,也许 api.php 没有向我们响应用户数据?这种情况还有其他解决方案吗?
  • 您可以打印您的回复以查看您从服务器获得了什么
  • 我得到了结果:“成功”和消息:“更新成功”。但是没有获取到用户数据,所以所有的标签显示都是空的。是否需要在 API.php 中更改某些内容?如果可以快速更改更好...
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-12-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多