swift - 获取和追加Firebase值的函数返回一个空字符串

时间:2017-04-01 08:20:37

标签: arrays swift function firebase

我正在尝试创建一个函数来抓取Firebase中给定用户UID的类别子键,将它们附加到数组中,然后最终将它们连接成一个长字符串。一切正常,直到observeSingleEvent函数完成并且返回值为空。这是我的代码:

let referenceDatabase = FIRDatabase.database().reference()

func fetchBuddyInfo(category: String, buddyId: String) -> 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: ",")
    })
    return buddyInterests
}

我认为它与observeSingleEvent函数的嵌套范围有关,因为buddyInterests在运行函数后似乎失去了它的值,但是我无法弄清楚如何将值拉出来。

1 个答案:

答案 0 :(得分:0)

问题

observeSingleEvent(of:with:)是一个异步操作,这意味着它可以在执行函数后返回。这就是为什么在你的情况下你总是得到一个空字符串作为返回值

解决方案

因此,在您的情况下,您可以创建这样的完成处理程序:

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

并按照以下方式调用您的函数:

fetchBuddyInfo(category: categoryString, buddyId: buddyId) { (buddyInfoString) in
  // do whatever you want with your buddyInfoString
}