How to write to a variable from within the Firebase getDocument function (Swift)

人走茶凉 提交于 2021-02-09 07:08:02

问题


I want to read a document, get a field from that document, and set a variable to that field's value

I expected my variable declared outside the Firebase getDocument function to be written to. The actual results are that the variable is being written to within the Firebase getDocument function but outside the function it is empty.

Here's what I have tried:

[1]: Modifying variable within firebase function - this didn't work for me because I can't translate it well with my current Swift skills

[2]: How to set variables from a Firebase snapshot (swift) - this didn't work for me because the implementation deviates by a lot from what I have right now


//open the user Firebase database by documentID
     let userDocument = userdb.collection("users").document(userDocumentId)

     var userjobsData = [[String:Any]]()

     userDocument.getDocument { (docums, error)  in

         if let docum = docums, docum.exists {

         //grab all jobs data
         userjobsData = docum.get("jobData") as! [[String:Any]]

         //sort jobs by category in alphabetical order
         userjobsData = (userjobsData as NSArray).sortedArray(using: [NSSortDescriptor(key: "category", ascending: true)]) as! [[String:AnyObject]]

         }
        //Here userjobsData contains data
        print(userjobsData)
     }
     //Here userjobsData is empty
     print(userjobsData)


回答1:


Actually what is happening in your case Firebase fetching data is asynchronous task and takes some time to fetching data , in mean time you are reading your userjobsData which is empty since Firebase request has not been completed .

What you can do is actually perform needed operation after fetching data from firebase .

Adding Sample code for your reference.

private func fetchDataFromFirebase(){

  let userDocument = userdb.collection("users").document(userDocumentId)

     var userjobsData = [[String:Any]]()

     userDocument.getDocument { (docums, error)  in

         if let docum = docums, docum.exists {

         //grab all jobs data
         userjobsData = docum.get("jobData") as! [[String:Any]]

         //sort jobs by category in alphabetical order
         userjobsData = (userjobsData as NSArray).sortedArray(using: [NSSortDescriptor(key: "category", ascending: true)]) as! [[String:AnyObject]]

          self.perfomAction(firebaseResult : userjobsData)
          // now pass this data to your need function like
         }

  }
}

private func perfomAction(firebaseResult : [[String:Any]]){
  // perform your job here
}


来源:https://stackoverflow.com/questions/59796930/how-to-write-to-a-variable-from-within-the-firebase-getdocument-function-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!