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

查看:62
本文介绍了在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相关联的文档,然后在该文档中打印名字"字段.

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没有异步或等待状态.

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天全站免登陆