firebaseswiftuigeolocationcllocationmanagercllocation

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


Hello I am stuck and have tried to google and research but am not having any luck. The user location is saying its nil. I am trying to send it to Firebase database to show the users location. When I print out the userLocation.coordinate.latitude manually it shows me the correct coordinates in the console. I have tried to put:

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

To possibly unwrap the userlocation but no luck.

I am getting an ERROR:

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

Current CODE:

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

EDIT:

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

Solution

  • So I figured it out with the help of you @workingdog . The if let gave me the error: Initializer for conditional binding must have Optional type, not 'CLLocationDegrees' (aka 'Double')

    So I did some digging on swiftui forums and found this solution for forcing an unwrap. 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")
    }