swift - Function that fetches and appends Firebase values returns an empty string

后端 未结 1 371
眼角桃花
眼角桃花 2021-01-27 17:08

I\'m trying to create a function that grabs the category children\'s keys of a given user UID in Firebase, appends them to an array and then finally joins them together into one

相关标签:
1条回答
  • 2021-01-27 17:30

    Problem

    observeSingleEvent(of:with:) is an asynchronous operation, which means that it can return later after executing the function. That's why in your case you get always an empty String as return value

    Solution

    So in your case you can create a completion handler like this:

    func fetchBuddyInfo(category: String, buddyId: String, completion: @escaping (String) -> ()) {
    
      var buddyInterestsArray = [String]()
      var buddyInterests = String()
    
      referenceDatabase.child("Users").child(buddyId).child(category).observeSingleEvent(of: .value, with: { (categorySnap) in
    
        for categoryItems in categorySnap.children.allObjects as! [FIRDataSnapshot] {
    
          buddyInterestsArray.append(categoryItems.key)
        }
    
        buddyInterests = buddyInterestsArray.joined(separator: ",")
    
        completion(buddyInterests)
      })
    }
    

    And call your function like this:

    fetchBuddyInfo(category: categoryString, buddyId: buddyId) { (buddyInfoString) in
      // do whatever you want with your buddyInfoString
    }
    
    0 讨论(0)
提交回复
热议问题