Storing asynchronous Cloud Firestore query results in Swift

前端 未结 1 1293
温柔的废话
温柔的废话 2020-12-22 07:30

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 a

相关标签:
1条回答
  • 2020-12-22 08:17

    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)
           }
    }
    

    Call

    convertToNames(arr:<#arr#>) { res in
         print(res)
    }
    
    0 讨论(0)
提交回复
热议问题