更新firebase中字典中的单个值 - Swift项目

时间:2016-04-30 14:17:59

标签: ios swift dictionary firebase

我正在使用swift和firebase处理iOS应用程序。 我试图让用户使用单独的按钮将他的电子邮件和密码以及存储在firebase中的其余信息更改到同一个视图控制器中。

以下是仪表板中一位用户的示例:

    {
     "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/"
        }
      }
    }

以下是代码:

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)

    }
}

在每个按钮中,我正在更新firebase中的整个字典!哪个错了!

如何在firebase中仅更新电子邮件按钮中的电子邮件值, 和提供者密码按钮?

4 个答案:

答案 0 :(得分:24)

评论中的这个问题和答案帮助了我。由于没有正式回答的问题,我将添加一个更新的代码,因为评论中的一个已被弃用。

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

这对我很有用。

答案 1 :(得分:1)

您只需导航到要更新的单个值,然后使用setValue(此处为其赋值) 这是一个非常简单的例子:

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)

}

//添加一个更新的按钮名称或whatEver,并将其作为Action

连接
@IBAction func updateData(_ sender: Any) {

    DBprovider.instance.DBRef.child("Data").child(key.key).child("id").setValue(111)


}

答案 2 :(得分:0)

  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...")
                }
            }

答案 3 :(得分:0)

此代码可在快速4和5中正常工作

func updateAnyFirebaseVale(_ param :  String){

    if let id = self.currentId{

        let val =  Database.database().reference(fromURL:
            "Your_URL").child("CHILD NODE NAME").child("ID YOU WANT TO UPDATE ")

        val.updateChildValues(["specific param name to update like password name etc" : "value of param"])

        let alert = UIAlertController(title: "Message Header", message: "", preferredStyle: .alert)

        alert.addAction(UIAlertAction(title: "Done", style: .default, handler: { (alert) in


        }))

        self.present(alert,animated: true)

}