Ishan Jain Ishan Jain - 1 year ago 285
iOS Question

How to save coordinates to Firebase Swift 2

I want to save a set of latitude and longitude coordinates to Firebase, but whenever my app runs through this code it crashes!

let userID: String = (FIRAuth.auth()?.currentUser?.uid)!
let lat: Double = (locationManager.location?.coordinate.latitude)!
let lon: Double = (locationManager.location?.coordinate.longitude)!

self.ref.child("Location").child(userID).setValue(["Latitude": lat, "Longitude": lon])

Is there anyway I can fix this and save it properly and efficiently?

Answer Source

Make sure of two things :-

1.) your viewController inherits from CLLocationManagerDelegate and has its delegate set to self in viewDidLoad

2.) your info.plist has these keys added to them :-

NSLocationAlwaysUsageDescription --- I need Location

NSLocationWhenInUseUsageDescription --- I need Location

privacy - location usage description --- I need Location

class MapViewController: UIViewController , CLLocationManagerDelegate...{


let locationManager   = CLLocationManager()

func viewDidLoad(){

    locationManager.delegate = self

    locationManager.desiredAccuracy = kCLLocationAccuracyBest
    locationManager.distanceFilter = kCLDistanceFilterNone


//Call these functions for updating the getting the values of current  location

   func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) {

    if status == .AuthorizedWhenInUse {

        print("authorised call came . . . . ")
        mapView.myLocationEnabled = true


func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {

    if let location = locations.first {

    print("target position : =  \(location.coordinate)")
    print(locationManager.location!.coordinate.latitude) = GMSCameraPosition(target: location.coordinate, zoom: 15, bearing: 0, viewingAngle: 0)
    self.FIRDatabase.database().reference().child("Location").child(FIRAuth.auth()!.currentUser!.uid).setValue(["Latitude": locationManager.location!.coordinate.latitude, "Longitude": locationManager.location!.coordinate.longitude])


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download