从一个从firebase

时间:2016-07-14 01:49:51

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

我正在尝试从Firebase检索数据并将该数据存储在检索该数据的闭包之外。

    var stringNames = [String] ()
    ref?.observeEventType(.Value, withBlock: { snapshot in
        var newNames: [String] = []
        for item in snapshot.children {
            if let item = item as? FIRDataSnapshot {
                let postDict = item.value as! [String: String]
                newNames.append(postDict["name"]!)
            }
        }
        stringNames = newNames
    })
    print(stringNames)

stringNames返回空,但是当我从闭包内打印时,它有正确的数据。非常感谢任何帮助,谢谢!

1 个答案:

答案 0 :(得分:8)

这是因为当您从Firebase获取数据时,该调用是异步的。你能做什么:

选项1 - 在闭包内设置逻辑(就像你在封闭内部打印var一样)。

选项2 - 定义您自己的闭包,用于接收您的数据,如:

func myMethod(success:([String])->Void){

    ref?.observeEventType(.Value, withBlock: { snapshot in
        var newNames: [String] = []
        for item in snapshot.children {
            if let item = item as? FIRDataSnapshot {
                let postDict = item.value as! [String: String]
                newNames.append(postDict["name"]!)
            }
        }
        success(newNames)
    })
}

选项3 - 使用委托模式

protocol MyDelegate{
     func didFetchData(data:[String])
}

class MyController : UIViewController, MyDelegate{

    func myMethod(success:([String])->Void){
        ref?.observeEventType(.Value, withBlock: { snapshot in
           var newNames: [String] = []
           for item in snapshot.children {
               if let item = item as? FIRDataSnapshot {
                   let postDict = item.value as! [String: String]
                   newNames.append(postDict["name"]!)
               }
            }
            self.didFetchData(newNames)
        })
    }

    func didFetchData(data:[String]){
        //Do what you want
    }

}