iOS Firebase 异步数据检索到数组

标签 ios swift firebase asynchronous

我尝试将数据从 Firebase 检索到数组中。因为它是异步运行的,所以我想在我的 CollectionView 中显示的结果是一个延迟,直到我来回切换。我对 iOS 中的异步函数非常陌生。请帮助我完成我的代码。

    ref = Database.database().reference(withPath: "MyTest/Video")
        ref?.observeSingleEvent(of: .value, with: { snapshot in

            if !snapshot.exists() { return }

            if let result = snapshot.children.allObjects as? [DataSnapshot] {
                for child in result {
                    let autoID = child.key as String //get autoID

                    let title = snapshot.childSnapshot(forPath: "\(autoID)/Title").value
                    let url = snapshot.childSnapshot(forPath: "\(autoID)/URL").value
                    let views = snapshot.childSnapshot(forPath: "\(autoID)/Views").value

                    self.arrayAllTitle.append(title as! String)
                    self.arrayAllId.append(url as! String)
                    self.arrayAllDesc.append(views as! String)
                }
            }


        })

最佳答案

您需要在检索数据后重新加载集合,因此在 for 循环调用 reloadData()

之后
for child in result {

}

self.collectionView.reloadData()

//

func getValueFromDatabase(completion: @escaping (_ status: Bool) -> Void){

    ref = Database.database().reference(withPath: "MyTest/Video")
    ref?.observeSingleEvent(of: .value, with: { snapshot in

        if !snapshot.exists() { return }

        if let result = snapshot.children.allObjects as? [DataSnapshot] {
            for child in result {
                let autoID = child.key as String //get autoID

                let title = snapshot.childSnapshot(forPath: "\(autoID)/Title").value
                let url = snapshot.childSnapshot(forPath: "\(autoID)/URL").value
                let views = snapshot.childSnapshot(forPath: "\(autoID)/Views").value

                self.arrayAllTitle.append(title as! String)
                self.arrayAllId.append(url as! String)
                self.arrayAllDesc.append(views as! String)
            }

            completion(true)
        }
        else {
            completion(false)
        }
    })
}

//

self.getValueFromDatabase { (status) in

    if status {
       // success 
    }
 }

关于iOS Firebase 异步数据检索到数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50377871/

相关文章:

ios - 带有颜色和居中文本的 UIImage

ios - 如何打印相机闪光灯是否打开(Swift 4)

java - 检查用户是否通过密码验证或使用某些提供商

android - 挂起函数只能在协程体内调用

带有 Symfony 1.4 的 Iphone 应用程序

ios - Uber 是如何在 WatchKit 中实现这个 UI 的?

javascript - 将 NSTaggedPointerString 转换为字符串

ios swift制作表列表不断收到关于nill的错误

java - 在 Android 上动态更改 Firebase 查询引用的限制

ios - pod lib lint 中不包含框架头文件