Swift:如何为从我的firebase数据库中抓取数据的函数实现完成处理程序

时间:2018-05-22 02:14:11

标签: swift firebase firebase-realtime-database completionhandler

我编写了代码来从我的firebase数据库中检索数据并将其附加到名为toWatchMoviesListInitial的数组中。但是,在附加数据后打印出toWatchMoviesListInitial的值时,它什么都没打印出来 我被告知这是因为这是异步的。处理这个问题可以使用完成处理程序 但是,我是swift的新手,我不知道如何实现完成处理程序。如果你能告诉我如何去做,我将不胜感激。这是我的代码:

func initialiseTicketsList() {
    ref = Database.database().reference()
    let uid = Auth.auth().currentUser?.uid
    ref?.child("users").child(uid!).observeSingleEvent(of: .value, with: { (snapshot) in
        if let dictionary = snapshot.value as? [String: AnyObject] {
            let userDict = dictionary["watchList"] as? [String:String]
            for (_,myValue) in userDict! {
                if myValue.contains("ignore"){
                }
                else{
                    print(type(of: myValue))
                    self.toWatchMoviesListInitial.append(myValue)
                }
            }
        }
    }, withCancel: nil)

    print(toWatchMoviesList)     //prints empty when it shouldn't
}

1 个答案:

答案 0 :(得分:0)

func initialiseTicketsList(completionHandler: @escaping ([String]) -> Void) {
    ref = Database.database().reference()
    let uid = Auth.auth().currentUser?.uid
    ref?.child("users").child(uid!).observeSingleEvent(of: .value, with: { (snapshot) in
        if let dictionary = snapshot.value as? [String: AnyObject] {
            let userDict = dictionary["watchList"] as? [String:String]
            var toWatchMoviesListInitial: [String] = [] //local variable
            for (_,myValue) in userDict! {
                if myValue.contains("ignore"){
                }
                else{
                    print(type(of: myValue))
                    toWatchMoviesListInitial.append(myValue)
                }
            }
            completionHandler(toWatchMoviesListInitial) // callback invoked.
        }
    }, withCancel: nil)
}

// wherever you call initialiseTicketsList, call with completionHandler
initialiseTicketsList(completionHandler: {movieList in
 self.toWatchMoviesList = movieList // or append based on your usecase.
}

请在here

了解closure@escaping