Home > OS >  Get users current location and upload it to firebase
Get users current location and upload it to firebase

Time:02-04

I am trying to get the users current location in swifti and then upload it to firebase, but nothing seems to be uploaded

I tried adding print commands to the code to check whether I was getting the location but nothing was printed to the terminal, here is my code:

import MapKit
import FirebaseFirestore

struct Maps: View {
    @State private var location = CLLocationCoordinate2D()

    var body: some View {
        Text("Hello World")
            .onAppear {
                let manager = LocationManager()
                manager.getLocation { location in
                    self.location = location
                    print("Latitude: \(location.latitude), Longitude: \(location.longitude)")
                }
            }
    }
}

class LocationManager: NSObject, CLLocationManagerDelegate {
    let locationManager = CLLocationManager()

    func getLocation(completion: @escaping (CLLocationCoordinate2D) -> ()) {
        locationManager.delegate = self
        locationManager.requestWhenInUseAuthorization()
        locationManager.startUpdatingLocation()

        self.completion = completion
    }

    private var completion: ((CLLocationCoordinate2D) -> ())?

    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        guard let location = locations.last else { return }

        let db = Firestore.firestore()
        let locationRef = db.collection("locations").document()
        locationRef.setData([
            "latitude": location.coordinate.latitude,
            "longitude": location.coordinate.longitude,
            "identifier": UUID().uuidString
        ])

        locationManager.stopUpdatingLocation()
        completion?(location.coordinate)
    }
}

struct Maps_Previews: PreviewProvider {
    static var previews: some View {
        Maps()
    }
} 

I added Privacy - Request when in use.. to info, so I don’t know what the problem is, I am not getting any errors

CodePudding user response:

This code

.onAppear {
    let manager = LocationManager()
    // ...
}

creates and then immediately discards a LocationManager, which means that the object does not live long enough in memory to even receive one callback to the delegate method.

Move manager up to be a propery of Maps to let it stay in memory as long as the view itself.

  • Related