【问题标题】:Function returning before completing [Swift] [Firebase]在完成 [Swift] [Firebase] 之​​前返回的函数
【发布时间】:2020-09-26 05:42:35
【问题描述】:

我正在尝试从 Google Firebase 数据库中读取数据,但我意识到我的函数在读取数据之前就返回了。 这是代码

func getFirebaseCoordinates(increment : Int) -> CLLocationCoordinate2D {
    var coordinates : CLLocationCoordinate2D = CLLocationCoordinate2D()
    let ref = Database.database().reference()

    ref.child("\(getPilot() + String(increment))/Latitude").observeSingleEvent(of: .value) { (snapshot) in
        let lat = snapshot.value as? CLLocationDegrees
        coordinates.latitude = lat ?? -1.0
        print(coordinates.latitude)
    }
    ref.child("\(getPilot() + String(increment))/Longitude").observeSingleEvent(of: .value) { (snapshot) in
        let long = snapshot.value as? CLLocationDegrees
        coordinates.longitude = long ?? -1.0
        print(coordinates.longitude)
    }
    print(coordinates)
    return coordinates
}

当我检索坐标时,我打印它们,然后在函数结束时,我打印我返回的内容。我实际上循环了这个函数两次,在我什至可以打印出我检索的第一个坐标之前,我已经打印了两个返回语句,它们的输出为“CLLocationCoordinate2D(latitude: 0.0, longitude: 0.0)” 有什么想法吗?谢谢!

【问题讨论】:

    标签: swift firebase function coordinates


    【解决方案1】:

    您需要在异步函数中返回完成处理程序,因为在获得异步调用结果之前返回执行

    func getFirebaseCoordinates(increment : Int,completion: @escaping (CLLocationCoordinate2D)-> Void )  {
        var coordinates : CLLocationCoordinate2D = CLLocationCoordinate2D()
        let ref = Database.database().reference()
    
        ref.child("\(getPilot() + String(increment))/Latitude").observeSingleEvent(of: .value) { (latitudeSnapshot) in
    
            let lat = latitudeSnapshot.value as? CLLocationDegrees
            coordinates.latitude = lat ?? -1.0
    
            ref.child("\(getPilot() + String(increment))/Longitude").observeSingleEvent(of: .value) { (LongitudeSnapshot) in
                 let long = LongitudeSnapshot.value as? CLLocationDegrees
                 coordinates.longitude = long ?? -1.0
    
                completion(coordinates)
             }
    
    
    
        }
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-02-17
      • 1970-01-01
      • 2021-08-02
      • 1970-01-01
      • 2023-02-23
      • 1970-01-01
      • 2014-07-10
      • 1970-01-01
      相关资源
      最近更新 更多