swift-获取和附加Firebase值的函数返回一个空字符串 [英] swift - Function that fetches and appends Firebase values returns an empty string

查看:59
本文介绍了swift-获取和附加Firebase值的函数返回一个空字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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 long string. Everything works well until the observeSingleEvent function completes and the return value is empty. Here's my code:

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在运行该函数后似乎会丢失其值,但是我不知道如何提取该值.

I think it has something to do with the nested scope of the observeSingleEvent function since buddyInterests seems to lose its value after running the function, but I can't figure out how to pull the value out.

推荐答案

问题

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

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

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

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

并这样调用您的函数:

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

这篇关于swift-获取和附加Firebase值的函数返回一个空字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆