0

Im using google places api to and use the coordinates to put an annotation on an apple maps.

What I want to do now is to translate coordinates to name and address and use it for the Ekreminder. This is my code so far but i get the error "fatal error: unexpectedly found nil while unwrapping an Optional value" when i try to run it:

    addLocationReminderViewController.name = self.mapItemData.placemark.name

    // Construct the address
    let dic = self.mapItemData.placemark.addressDictionary as Dictionary!
    let city = dic["City"] as! String
    let state = dic["State"] as! String
    let country = dic["Country"] as! String
    addLocationReminderViewController.address = "\(city), \(state), \(country)"
}

edit this is how im getting the info:

                    if data != nil{
                    let dic = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableLeaves) as!  NSDictionary

                    let lat = dic["results"]?.valueForKey("geometry")?.valueForKey("location")?.valueForKey("lat")?.objectAtIndex(0) as! Double
                    let lon = dic["results"]?.valueForKey("geometry")?.valueForKey("location")?.valueForKey("lng")?.objectAtIndex(0) as! Double
                    let point = MKPointAnnotation()
                    point.coordinate = CLLocationCoordinate2D(latitude: lat, longitude: lon)
                    point.title = self.resultsArray[indexPath.row]
                    let region = MKCoordinateRegion(center: point.coordinate, span: MKCoordinateSpan(latitudeDelta: 0.1, longitudeDelta: 0.1))
                    dispatch_async(dispatch_get_main_queue(), { () -> Void in
                        self.mapView.setRegion(region, animated: true)
                        self.mapView.addAnnotation(point)
                        self.mapView.selectAnnotation(point, animated: true)
                        //
                        let placemark = MKPlacemark(coordinate: point.coordinate, addressDictionary: nil)
                        let mapItem = MKMapItem(placemark: placemark)
                        self.mapItemData = mapItem
                        //
                    })
Tim
  • 69
  • 10

1 Answers1

0

You are 'blindly' casting dictionary references for "City", "State" and "Country" to String using as!. If any one of them doesn't exist in the dictionary or isn't a string then you get your fatal error.

How do you plan to handle a malformed dictionary? You could use

if let city    = dic["City"]    as? String,
   let state   = dic["State"]   as? String,
   let country = dic["Country"] as? String {
  // you now have your values
  addLocationReminderViewController.address = "\(city), \(state), \(country)"
}
else {
 // something is wrong
}
GoZoner
  • 67,920
  • 20
  • 95
  • 145