如何异步使用Firebase?数据库读数给出奇怪的结果

时间:2017-10-21 17:03:51

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

我编写了以下函数来搜索我的Firebase数据库,我还研究了使用调试语句并使用断点进行测试,看看这个函数正在提取正确的数据。但是当我最后返回数组时,数组是空的。据我所知,这是由于firebase的异步性质。在将数据添加到数组之前,该函数已结束。我如何解决这个问题,以便它可以按预期工作,我想返回一个项目数组,然后我可以将其用于其他功能。

static func SearchPostsByTags(tags: [String]) -> [Post]{
    var result = [Post]()

    let dbref = FIRDatabase.database().reference().child("posts")

    dbref.observeSingleEvent(of: .value, with: { snap in
        let comps = snap.value as! [String : AnyObject]

        for(_, value) in comps {
            let rawTags = value["tags"] as? NSArray

            let compTags = rawTags as? [String]

            if compTags != nil {

                for cTag in compTags! {
                    for tag in tags {
                        if (tag == cTag) {
                            let foundPost = Post()
                            foundPost.postID = value["postID"] as! String
                            foundPost.title = value["title"] as! String

                            result.append(foundPost)
                        }
                    }
                }
            }
        }
    })
    return result
}

}

1 个答案:

答案 0 :(得分:0)

您将在array来电结束前返回async。您应该在异步调用中填充数组,然后调用另一个提供结果的方法。

static func SearchPostsByTags(tags: [String]) {
    let dbref = FIRDatabase.database().reference().child("posts")
    dbref.observeSingleEvent(of: .value, with: { snap in
        let comps = snap.value as! [String : AnyObject]
        var result = [Post]()
        for(_, value) in comps {
            let rawTags = value["tags"] as? NSArray

            let compTags = rawTags as? [String]

            if compTags != nil {

                for cTag in compTags! {
                    for tag in tags {
                        if (tag == cTag) {
                            let foundPost = Post()
                            foundPost.postID = value["postID"] as! String
                            foundPost.title = value["title"] as! String

                            result.append(foundPost)
                        }
                    }
                }
            }
        }
       // Call some func to deliver the finished result array
       // You can also work with completion handlers - if you want to try have a look at callbacks / completion handler section of apples documentation
       provideTheFinishedArr(result)
    })
}