Updating a single value in a dictionary in firebase – Swift project

I’m working on iOS application using swift and firebase.
I’m trying to let the user change his email and password and the rest of his information stored in firebase in the same view controller using separate buttons.

Here’s example of one user from the dashboard:

  • How can we create our own plist file in a Xcode project?
  • In new Firebase, how to use multiple config file in xcode?
  • Swift iOS: Firebase Paging
  • Firebase listener when app is in the background
  • Firebase erroneously shows deleted data / Swift 3 / Xcode 8.2
  • Pass value with action sheet button
  •     {
         "Users" : {
           "08e5443c-cdde-4fda-8733-8c4fce75dd34" : {
             "BusinessName" : "looliCake",
             "Category" : "Cooking",
             "City" : "Riyadh",
             "ContactMe" : "05551233210",
             "Details" : "many flaiver choose",
             "Email" : "loolicack@gmail.com",
             "PhoneNumber" : "05551233210",
             "Provider" : "123",
             "ShortDescription" : "best pop cake ever . ",
             "Website1" : "www.looliCack.com",
             "Website2" : "https://www.instagram.com/loolicack/"
            }
          }
        }
    

    Here’s the code:

    let mainpass = NSUserDefaults.standardUserDefaults().objectForKey("password") as? String
    let mainEmail = NSUserDefaults.standardUserDefaults().objectForKey("Email") as? String
    
    
    
    @IBAction func EditEmail(sender: AnyObject) {
    
        if EmailAddressTF.text==""
        {
            let alert = UIAlertController(title: "Oops!", message:"Make sure to fill in all required textfields", preferredStyle: .Alert)
            alert.addAction(UIAlertAction(title: "OK", style: .Default) { _ in })
            self.presentViewController(alert, animated: true){}
        }
        else
        {
            let isEqu = (mainEmail == self.EmailAddressTF.text)
            if(isEqu == true) {
    
            } else {
                let ref = Firebase(url: "https://businesswallet.firebaseio.com/")
    
                ref.changeEmailForUser(mainEmail, password: mainpass, toNewEmail: self.EmailAddressTF.text, withCompletionBlock: { error in
    
                    if error != nil {
    
                        if let errorCode = FAuthenticationError(rawValue: error.code) {
    
                            switch (errorCode) {
                            case .EmailTaken:
                                print("Email taken")
                                let alert = UIAlertController(title: "Oops!", message:"Sorry,Email taken", preferredStyle: .Alert)
                                alert.addAction(UIAlertAction(title: "OK", style: .Default) { _ in })
                                self.presentViewController(alert, animated: true){}
    
                            case .InvalidEmail:
                                print("invalid email")
                                let alert = UIAlertController(title: "Oops!", message:"invalid email", preferredStyle: .Alert)
                                alert.addAction(UIAlertAction(title: "OK", style: .Default) { _ in })
                                self.presentViewController(alert, animated: true){}
    
    
                            case .NetworkError:
                                print("Network Error")
                                let alert = UIAlertController(title: "Oops!", message:"Network error, check your connection", preferredStyle: .Alert)
                                alert.addAction(UIAlertAction(title: "OK", style: .Default) { _ in })
                                self.presentViewController(alert, animated: true){}
    
                            default:
                                print("Unknown Error")
                                let alert = UIAlertController(title: "Oops!", message:"Unknown Error", preferredStyle: .Alert)
                                alert.addAction(UIAlertAction(title: "OK", style: .Default) { _ in })
                                self.presentViewController(alert, animated: true){}
                            }
                        }
    
    
    
    
    
                    } else {
    
                        NSUserDefaults.standardUserDefaults().setValue(self.EmailAddressTF.text, forKey: "Email")
                        print("Email changed successfully")
    
                        let newUser = [
                            "Provider": self.PasswordTF.text!,
                            "Email": self.EmailAddressTF.text,
                            "BusinessName": self.BusinessNameTF.text ,
                            "ShortDescription" : self.ShortDescriptionTF.text,
                            "Category" : self.itemSelected,
                            "City" : self.CityTF.text,
                            "ContactMe" : self.ContactMeTF.text,
                            "PhoneNumber" : self.PhoneNumberTF.text,
                            "Website1": self.Website1TF.text,
                            "Website2": self.Website2TF.text,
                            "Details": self.DetailsTV.text
                        ]
    
    
                        self.ref.childByAppendingPath("Users").childByAppendingPath(self.ref.authData.uid).updateChildValues(newUser)
                        self.navigationController?.popViewControllerAnimated(true)
    
                    }
    
                })
    
            } //Big Else
    
    
        }
    
    
    
    } //EditEmailButton
    
    
    
    
    @IBAction func EditPassword(sender: AnyObject) {
    
        if  PasswordTF.text==""
        {
            let alert = UIAlertController(title: "Oops!", message:"Make sure to fill in all required textfields", preferredStyle: .Alert)
            alert.addAction(UIAlertAction(title: "OK", style: .Default) { _ in })
            self.presentViewController(alert, animated: true){}
        }
        else
        {
            if RepasswordTF.text != PasswordTF.text
            {
                let alert = UIAlertController(title: "Oops!", message:"You Entered Different Passwords", preferredStyle: .Alert)
                alert.addAction(UIAlertAction(title: "OK", style: .Default) { _ in })
                self.presentViewController(alert, animated: true){}
            }
            else {
    
    
                ref.changePasswordForUser( NSUserDefaults.standardUserDefaults().objectForKey("Email") as? String, fromOld: NSUserDefaults.standardUserDefaults().objectForKey("password") as? String, toNew: self.PasswordTF.text)
                {
    
                    (ErrorType) -> Void in
                    if ErrorType != nil {
                        print(ErrorType)
                        print("There was an error processing the request")
                    }
                    else
                    {
    
                        NSUserDefaults.standardUserDefaults().setValue(self.PasswordTF.text, forKey: "password")
                        print("Password changed successfully")
    
                    }
    
                }
    
    
                let newUser = [
                    "Provider": self.PasswordTF.text!,
                    "Email": self.EmailAddressTF.text,
                    "BusinessName": self.BusinessNameTF.text ,
                    "ShortDescription" : self.ShortDescriptionTF.text,
                    "Category" : self.itemSelected,
                    "City" : self.CityTF.text,
                    "ContactMe" : self.ContactMeTF.text,
                    "PhoneNumber" : self.PhoneNumberTF.text,
                    "Website1": self.Website1TF.text,
                    "Website2": self.Website2TF.text,
                    "Details": self.DetailsTV.text
                ]
    
    
                self.ref.childByAppendingPath("Users").childByAppendingPath(self.ref.authData.uid).updateChildValues(newUser)
                self.navigationController?.popViewControllerAnimated(true)
    
            }
    
    
        } //else
    
    
    }
    
    
    
    @IBAction func EditBusinessInfo(sender: AnyObject) {
    
        if BusinessNameTF.text==""
        {
            let alert = UIAlertController(title: "Oops!", message:"Make sure to fill in all required textfields", preferredStyle: .Alert)
            alert.addAction(UIAlertAction(title: "OK", style: .Default) { _ in })
            self.presentViewController(alert, animated: true){}
        }
        else
        {
    
            let newUser = [
                "Provider": self.PasswordTF.text!,
                "Email": self.EmailAddressTF.text,
                "BusinessName": self.BusinessNameTF.text ,
                "ShortDescription" : self.ShortDescriptionTF.text,
                "Category" : self.itemSelected,
                "City" : self.CityTF.text,
                "ContactMe" : self.ContactMeTF.text,
                "PhoneNumber" : self.PhoneNumberTF.text,
                "Website1": self.Website1TF.text,
                "Website2": self.Website2TF.text,
                "Details": self.DetailsTV.text
            ]
    
    
            self.ref.childByAppendingPath("Users").childByAppendingPath(self.ref.authData.uid).updateChildValues(newUser)
            self.navigationController?.popViewControllerAnimated(true)
    
        }
    }
    

    In each button, I’m updating the entire dictionary in firebase! Which’s wrong!

    How can I update in firebase only the email value in email button,
    and provider in password button?

    3 Solutions Collect From Internet About “Updating a single value in a dictionary in firebase – Swift project”

    This question and answer in the comments helped me out. Since there isn’t an official answered question, I will add one with updated code cause the one in the comments is deprecated.

    ref.child("yourKey").child("yourKey").updateChildValues(["yourKey": yourValue])
    

    This worked perfectly for me.

    you can simply navigate to that single value which you want to update then use setValue(and here give it the value)
    here is a very simple example :

    var key : FIRDatabaseReference!
    
    override func viewDidLoad() {
        super.viewDidLoad()
    
        // Do any additional setup after loading the view.
        addData()
    }
    
    
    
    func addData()
    {
    
        var data :Dictionary<String,Any> = ["name":"nawal","id":123]
       key =  DBprovider.instance.DBRef.child("Data").childByAutoId()
        key.setValue(data)
    
    }
    

    //add a button name it update or whatEver and connect it as Action

    @IBAction func updateData(_ sender: Any) {
    
        DBprovider.instance.DBRef.child("Data").child(key.key).child("id").setValue(111)
    
    
    }
    
      let path1 = FirebaseBaseUrl + "users/" + id
                let chilRef1 = FIRDatabase.database().referenceFromURL(path1)
                // chilRef1.updateChildValues(["status": "online"])
    
                chilRef1.updateChildValues(["status": "offline"]) { (error, ref) in
                    if(error != nil){
                        print("Error",error)
                    }else{
                        print("\n\n\n\n\nYou are Offline...")
                    }
                }