Firebase completion listeners in swift

后端 未结 3 1012
夕颜
夕颜 2020-12-18 13:38

How do you execute a completion listener for firebase in swift? It says there are completion listers for SetValue and UpdateValue in the docs but there is no example.

相关标签:
3条回答
  • 2020-12-18 13:42
    • For setValue in Firebase you can write completion blocks as below:

      let ref = Database.database().reference().child("somepath")
      ref.setValue("value") { (error, databaseRef) in
         if error != nil {
             print("Error for setting value")
         } else {
             print("Value set successfully.")
         }
      }
      
    • For updateValue in Firebase:

      let newKeyValueData:[String:Any] = ["key1":"value1", "key2":value2] as [String:Any]
      ref.updateChildValues(["someKey":"value"]) { (error, dbRef) in
         if error != nil {
             print("Error for updating value")
         } else {
             print("Value updated successfully.")
         }  
      }
      
    0 讨论(0)
  • 2020-12-18 13:51

    The completion of a setValue is handled within the {} block (closure). So once the attempt to setValue is made, the code within that block executes. error will be nil if none and snapshot will be the data that was written.

    let ref = self.myRootRef.child("some_path")
        ref.setValue("Hello", withCompletionBlock: { (error, snapshot) in
            if error != nil {
                print("oops, an error")
            } else {
                print("completed")
            }
        })
    

    gives a result of

    root_ref
       some_path: Hello
    

    and prints "completed"

    0 讨论(0)
  • 2020-12-18 14:04

    An example of using completion handler for setValue in firebase is given below. Similarly you can use completion handler for methods.

        func saveJob(completion:(Bool)-> Void) {
        FIRDatabase.database().reference().child("Job").setValue(["Title":self.title!,"Detail":self.details!], withCompletionBlock: { (error, ref) in
            debugPrint("Completed")
            completion(true)
        })
    }
    
    0 讨论(0)
提交回复
热议问题