在 Swift 中存储异步 Cloud Firestore 查询结果 [英] Storing asynchronous Cloud Firestore query results in Swift

查看:33
本文介绍了在 Swift 中存储异步 Cloud Firestore 查询结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Swift 5、SwiftUI 和 Firebase 进行一个简单的项目,该项目在数组中循环给定 id,在 Cloud Firestore 数据库中搜索每个 id,并将与该 id 关联的相应名称附加到一个新数组.

I am working on a simple project using Swift 5, SwiftUI and Firebase which cycles through given ids in an array, searching in the Cloud Firestore database for each id, and appending the corresponding name associated with the id to a new array.

这是我的数据库的图片:

Here is a picture of my database:

例如,我给了一个数组一些 id,然后对于给定数组中的每个元素,我获取与该 id 关联的文档,然后打印该文档中的firstname"字段.

For example, I am given an array a few ids, then for each element in the given array, I get the document associated with that id, then print the "firstname" field in that document.

但是,我想将检索到的每个名字"值存储到本地的单独数组中以备后用. 在 Javascript 中,我知道这是使用 await 和 async 函数完成的,但我通过无数小时的故障排除 Swift 没有 async 或 await.

However, I want to store each "firstname" value retrieved into a separate array locally for use later. In Javascript, I know this is done using await and async functions, but I found out through countless hours of troubleshooting that Swift doesn't have async or await.

这是我的代码:

func convertToNames(arr: [String]) -> [String]{

    var newArr : [String] = []

      for id in arr {
         let docRef = db.collection("users").document(id)
                 docRef.getDocument { (document, error) in
                     if let document = document, document.exists {
                         let dataDescription = document.data().map(String.init(describing:)) ?? "nil"
                         let data = document.get("firstname") ?? "nil"

                         print("gotten data: (data)")
                         newArr.append(String(describing: data))

                     } else {
                         print("Document does not exist")
                     }
            }
        }

    print("NEW ARRAY: (newArr)")
    return (newArr)
}

这段代码在完成后打印一个空数组,我明白为什么,但我不知道如何让它在 Swift 中工作.我今天花了大约 5 个小时来筛选 Firebase 文档、查看示例代码并筛选 Youtube,但没有任何资源能够在我需要的范围内解决这个问题.如果无法做到,请告诉我.

This code prints an empty array when finished, and I understand why but I just have no clue how to make it work in Swift. I've spent about 5 hours today sifting through the Firebase documentation, looking at example code, and sifting through Youtube, but none of the resources address this issue to the extent that I need. If it is impossible to do, please let me know.

推荐答案

除了完成你还需要一个调度组

You need a dispatch group in addition to a completion

func convertToNames(arr: [String],completion:@escaping(([String]) -> ())) {

    var newArr : [String] = []
    let g = DispatchGroup()
      for id in arr {
         let docRef = db.collection("users").document(id) 
                 g.enter()
                 docRef.getDocument { (document, error) in
                     if let document = document, document.exists {
                         let dataDescription = document.data().map(String.init(describing:)) ?? "nil"
                         let data = document.get("firstname") ?? "nil"

                         print("gotten data: (data)")
                         newArr.append(String(describing: data))
                         g.leave()
                     } else {
                         print("Document does not exist")
                         g.leave()
                     }
            }
        }

       g.notify(queue:.main) { 
         print("NEW ARRAY: (newArr)")
         completion(newArr)
       }
}

打电话

convertToNames(arr:<#arr#>) { res in
     print(res)
}

这篇关于在 Swift 中存储异步 Cloud Firestore 查询结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆