【问题标题】:Accessing data inside a closure after it has been completed完成后访问闭包内的数据
【发布时间】:2017-09-14 01:01:11
【问题描述】:

在将所有数据从 Firebase 添加到我的数组之后,我希望能够访问结果数组。每次我尝试这个,我都会得到 nil 数组。

目标是通过 Firebase 加载数组中的位置信息对象列表。

我的代码sn-p:

    class func loadData(){
    let root = FIRDatabase.database().reference()
    let locationSummary = root.child("LocSummary")

    locationSummary.observe(.childAdded,with: { (snapshot) in
        print("inside closure")
        let values = snapshot.value as? NSDictionary
        let name = values?["Name"] as? String ?? ""
        let rating = values?["Rating"] as? Int
        let latitude = values?["Latitude"] as? Double
        let longitude = values?["Longitude"] as? Double
        let musicType = values?["Music"] as? String ?? ""

        let loc = LocationInfo.init(name: name, rating: rating!, lat: 
latitude!, long: longitude!, musicTyp: musicType)
        resultsArray.append(loc)


    })

}

【问题讨论】:

  • 使用完成处理程序。
  • 检查更新的答案
  • 对您有帮助吗?

标签: swift asynchronous firebase firebase-realtime-database closures


【解决方案1】:

试试这样的:

class func loadData(completion: @escaping (_ location: LocationInfo) -> Void) {
    let root = FIRDatabase.database().reference()
    let locationSummary = root.child("LocSummary")

    locationSummary.observe(.childAdded,with: { (snapshot) in
        print("inside closure")
        let values = snapshot.value as? NSDictionary
        let name = values?["Name"] as? String ?? ""
        let rating = values?["Rating"] as? Int
        let latitude = values?["Latitude"] as? Double
        let longitude = values?["Longitude"] as? Double
        let musicType = values?["Music"] as? String ?? ""

        let loc = LocationInfo.init(name: name, rating: rating!, lat: 
latitude!, long: longitude!, musicTyp: musicType)
        completion(loc)
    })
}

在你的循环中添加如下内容:

func getArray(completion: @escaping (_ yourArray: [LocationInfo]) -> Void {
    var resultsArray = [LocationInfo]()
    let countOfLoadedItems = 0

    for item in yourArrayForCycle { // or your own cycle. Implement your logic
         loadData(completion: { location in
                         countOfLoadedItems += 1
                         resultsArray.append(location)
                         if countOfLoadedItems == yourArrayForCycle.count {
                             completion(resultsArray)
                         }
         })
    }
}

然后在函数中,你想要你的数据:

getArray(completion: { result in 
    yourArrayToFill = result
    // reload data etc..
})

类似的东西。使其适应您的解决方案。

希望对你有帮助

【讨论】:

  • 谢谢。这有帮助:)
  • @MinonWeerasinghe 很高兴听到:)
猜你喜欢
  • 2015-08-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-29
  • 1970-01-01
  • 2018-08-28
相关资源
最近更新 更多