Error: GeoPoint long and lat is nil not allowing me to send coordinates due to Unwrapping Optional Value

Error: GeoPoint long and lat is nil not allowing me to send coordinates due to Unwrapping Optional Value

你好,我被困住了,我已经尝试 google 和研究,但我没有任何运气。用户位置说它为零。我正在尝试将它发送到 Firebase 数据库以显示用户位置。当我手动打印 userLocation.coordinate.latitude 时,它会在控制台中显示正确的坐标。我试着把:

"location": GeoPoint(latitude: userLocation!.coordinate.latitude, longitude: userLocation!.coordinate.longitude)

可能解开 userlocation 但运气不好。

我遇到错误:

Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value

当前代码:

// Sending to firebase database the order but location: is giving the optional value fatal error, while everything else is sending correctly
db.collection("Users").document(Auth.auth().currentUser!.uid).setData([

    "ordered_weed": details,
    "total_cost": calculateTotalPrice(),
    "location": GeoPoint(latitude: userLocation.coordinate.latitude, longitude: userLocation.coordinate.longitude)

]) { (err) in

    if err != nil {
        self.ordered = false
        return
    }
    print("Success Order")
}

编辑:

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {      
    // reading user location and extracting details...
    self.userLocation = locations.last!
    self.extractLocation()
    // after extracting location logging in...
    self.login()
}

尝试这样的事情:

if let lat = userLocation.coordinate.latitude, let lon = userLocation.coordinate.longitude {
    db.collection("Users").document(Auth.auth().currentUser!.uid).setData([
        "ordered_weed": details,
        "total_cost": calculateTotalPrice(),
        "location": {"latitude": lat, "longitude": lon}
    ]) { (err) in
        
        if err != nil {
            self.ordered = false
            return
        }
        print("Success Order")
    }
}

不要将 if let lat = .... 放在 json 对象中。

所以我在你的帮助下弄明白了 @workingdog。 if let 给了我错误:条件绑定的初始化程序必须具有可选类型,而不是 'CLLocationDegrees'(又名 'Double')

所以我在 swiftui 论坛上进行了一些挖掘,发现了这个强制解包的解决方案。 https://forums.swift.org/t/forced-unwrapping/38829/4

db.collection("Users").document(Auth.auth().currentUser!.uid).setData([

    "ordered_weed": details,
    "total_cost": calculateTotalPrice(),
    "location": GeoPoint(latitude: (self.locationManager.location?.coordinate.latitude)!, longitude: (self.locationManager.location?.coordinate.longitude)!)
            
]) { (err) in
            
    if err != nil {
        self.ordered = false
        return
    }
    print("Success Order")
}