【问题标题】:Swift completion handler in class and function类和函数中的 Swift 完成处理程序
【发布时间】:2018-05-27 13:43:30
【问题描述】:

我有一个类,它的函数连接到 firestoreDB 并获取一些数据:

import UIKit
import CoreLocation
import Firebase

private let _singletonInstance = GetBottlesFromDB()

class GetBottlesFromDB: NSObject {

    class var sharedInstance: GetBottlesFromDB { return _singletonInstance }

    var Pins = [LayoutBottlesFromDB]()

    // MARK: - init
    override init() {
        super.init()
        populatePinList(completion: { pin in self.Pins } )
        //print("GET ALL PINS: \(Pins)")
    }


    func populatePinList(completion: @escaping ([LayoutBottlesFromDB]) -> ()) {

        Pins = []

        AppDelegate.ADglobalVar.db.collection("Bottles").whereField("pickupuser", isEqualTo: NSNull()).getDocuments { (querySnapshot, err) in
            if let err = err {
                print("Error getting documents: \(err)")
            } else {

                print("start getting documents:")
                for document in querySnapshot!.documents {
                    //print("\(document.documentID) => \(document.data())")
                    //print("\(document.documentID)")

                    let bottleID:String  = document.documentID
                    let bottlekind:Int = document.data()["bottle"] as! Int
                    var bottletitel:String
                    var bottlesub:String
                    var bottleurl:String = (document.data()["pic"] as? String)!


                    let pin = LayoutBottlesFromDB(document.data()["lat"] as! CLLocationDegrees, document.data()["long"] as! CLLocationDegrees, ID: bottleID, title: bottletitel, subtitle: bottlesub, type: bottlekind, url:bottleurl)

                    //print("GET DAATA from DB: \(pin)")
                    self.Pins.append(pin)

                } //for
                completion(self.Pins)
            } //else
        } //querysnap
    }//function
}//class

在我的 ViewController 中,我调用了这个函数。

for pin in GetBottlesFromDB.sharedInstance.Pins{
            print("Add Pin : \(pin)")
        }

我的问题是该函数将被调用但打印为空。 该函数不等待完成。我做错了什么?

【问题讨论】:

    标签: swift google-cloud-firestore


    【解决方案1】:

    您正在直接调用GetBottlesFromDB.sharedInstance.Pins,这不会等待populatePinList 方法的完成,这就是为什么您会出现空白所以您需要等待完成,或者您可以检查pins 变量中的数据是否可用需要像这样调用完成方法:

    GetBottlesFromDB.sharedInstance.populatePinList { (pins) in
                for pin in pins{
                    print("Add Pin : \(pin)")
                }
          }
    

    【讨论】:

      【解决方案2】:

      您的代码中没有任何内容等待异步方法的执行,所以这并不奇怪。此外,这将是一个糟糕的设计,因为它会阻止您的应用程序。此外,您的单例实现过于冗长,不能保证它保持单例,所以我建议将其更改为

      class GetBottlesFromDB {
      
          private(set) var Pins = [LayoutBottlesFromDB]()
      
          static let shared = GetBottlesFromDB()
      
          private init() {}
      
          // populatePinList as before
      }
      

      在您的视图控制器中,例如在viewDidLoad 做:

      override func viewDidLoad() {
          GetBottlesFromDB.shared.populatePinList { pins in
              pins.forEach { print("Add Pin: \(pin)") }
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-02-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-10-19
        • 1970-01-01
        相关资源
        最近更新 更多