platypus
platypus

Reputation: 111

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

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)

Upvotes: 3

Views: 196

Answers (1)

Vasucd
Vasucd

Reputation: 357

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
}

Upvotes: 2

Related Questions