Lester
Lester

Reputation: 731

How to change stored JSON data when i clicked save button? swift 3

I stored my user JSON data on "user" when I login. How can I change the value when i click save button?something like : crew_preferred_name to "Xiao Pang".

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

This is JSON Output

}
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" = "[email protected]";
"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;
}

This is the button code, I'm posting the action to php but don't know how to change or save the changes in "user" data. Without the code i have to login again to see the new update.

@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)
            }

        }

    }

}

Upvotes: 0

Views: 122

Answers (2)

Umair Afzal
Umair Afzal

Reputation: 5039

simply write this line after getting the latest data

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

In this way your "json" key will contain latest data and you can get it as

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

Upvotes: 1

David Pasztor
David Pasztor

Reputation: 54706

Don't use NSDictionary in Swift, use its native Swift counterpart, Dictionary.

Then you can access and change a value associated with a known key like this (you will need to make sure that the type of json is [String:Any] before saving it to UserDefaults for this code to work):

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

Upvotes: 2

Related Questions