Ishan Jain Ishan Jain - 3 months ago 83
Swift Question

How to convert String to CLLocationDegrees Swift 2

I am trying to convert a String that I am retrieving from Firebase and adding it as several annotations on Google Maps. Unfortuanately, my app is crashing whenever it goes through the current code:

ref = FIRDatabase.database().reference()
ref.child("Locations").observeSingleEventOfType(.Value, withBlock: { (snapshot) in
let lat = (snapshot.value!["Latitude"] as! NSString).doubleValue
let lon = (snapshot.value!["Longitude"] as! NSString).doubleValue



let complainLoc = CLLocationCoordinate2DMake(lat, lon)

let Coordinates = CLLocationCoordinate2D(latitude: lat, longitude: lon)

})


My JSON Tree

My Code Block Which Crashes

Here is the code I used for saving data to Firebase

FIRDatabase.database().reference().child("Location").child(FIRAuth.auth()!.currentUser!.uid).setValue(["Latitude": locationManager.location!.coordinate.latitude, "Longitude": locationManager.location!.coordinate.longitude])

Answer

Make sure when you are saving the values of lat and lon to the database you are saving them as Float or Double.. For retrieving use :

ref = FIRDatabase.database().reference()
    ref.child("Locations").observeEventType(.Value, withBlock: { (snapshot) in

   if snapshot.exists(){       

    if let locationDictionary = snapshot.value as [String : AnyObject]{

      for each in locationDictionary{          

     //each will bring you every location dictionary in your database for your every user
             let lat = each.value!["Latitude"] as! CLLocationDegrees
             let lon = each.value!["Longitude"] as! CLLocationDegrees
             let userId = each.key as! String

             let complainLoc = CLLocationCoordinate2DMake(lat, lon)

             let Coordinates = CLLocationCoordinate2D(latitude: lat, longitude: lon)   
       //Every time this for loop complete's itself it will generate a new set of Coordinates for each user   
        }
      }
   }
})
Comments