使用Swift在Firebase中完成异步任务

时间:2016-05-08 21:06:52

标签: swift firebase asynchronous firebase-realtime-database

我正在尝试编写一个函数,该函数将返回所有工作者的数组,但它在从firebase检索数据之前返回

这是我的代码:

func getWorkersList() -> ([Worker])
{
    let workersInfoRef = ref.childByAppendingPath("countries/\(userCountry)/cities/\(userCity)/workers/\(workFieldToRecieve)/")

    var workerList = [Worker]()
        workersInfoRef.queryOrderedByChild("name").observeSingleEventOfType(.Value, withBlock: { (snapshot) in

        print(snapshot.childrenCount)
        for rest in snapshot.children.allObjects as! [FDataSnapshot]{

            let workerInfo = Worker(uid: rest.value["uid"] as! String, name: rest.value["name"] as! String, city: rest.value["city"] as! String, profession: rest.value["profession"] as! String, phone: rest.value["phone"] as! String, email: rest.value["email"] as! String, country: rest.value["country"] as! String)
            workerList.append(workerInfo)

        }
        }) { (error) in
            print(error.description)
    }

    print(workerList.count)
    return workerList

}

2 个答案:

答案 0 :(得分:2)

这未经过测试......我只是动态编码,为您提供一般性的想法

为您的函数添加完成块/回调...

func getWorkersList(callback: ((data:[Worker]) ->Void )) {
    let workersInfoRef = ref.childByAppendingPath("countries/\(userCountry)/cities/\(userCity)/workers/\(workFieldToRecieve)/")

    var workerList = [Worker]()
    workersInfoRef.queryOrderedByChild("name")
       .observeSingleEventOfType(.Value, withBlock: { (snapshot) in

        print(snapshot.childrenCount)
        for rest in snapshot.children.allObjects as! [FDataSnapshot]{

            let workerInfo = Worker(uid: rest.value["uid"] as! String, name: rest.value["name"] as! String, city: rest.value["city"] as! String, profession: rest.value["profession"] as! String, phone: rest.value["phone"] as! String, email: rest.value["email"] as! String, country: rest.value["country"] as! String)
            workerList.append(workerInfo)

        }
        print(workerList.count)
        callback(workerList)

   }) { (error) in  print(error.description) }
}

传递完成块..

getWorkersList(callback: { (data:[Worker]) -> Void in 
    print(data)
})

答案 1 :(得分:0)

由于一个基本问题,您的问题中的代码不起作用:Firebase是异步的,无法调用它来返回像函数一样的值。

Firebase数据仅在获取它的块(内)完成后才可行。

应用程序代码的运行速度比互联网快得多,因此如果您告诉Firebase获取数据,然后尝试使用该数据块外的数据(例如返回workerList),则返回将在Firebase数据准备好之前启动,你有时会回来,也许永远都是。

那你做什么?您以异步方式编码。

比如说,你有一个tableView,它显示了一个工人列表。这是一个概念流程

tell firebase to get data withBlock {
    iterate over returned snapshot data to populate an array
    when done, tableView.reloadData
}

关键是利用Firebase的异步特性并编写适用于Firebase的代码。