Swift Reverse Geocoding using the Data

782 views Asked by At

I am successfully getting the current address details based on my location. It printlns perfectly. What is throwing me is how I extract the data from this call. I have tried passing, say the ZIP/Postcode, as local and even global variables but with no joy. The data only seems to exist within this call. How can I use it elsewhere?

// Get Address Information
    let geoCoder = CLGeocoder()
    let newLocation = CLLocation(latitude: valueLatitude, longitude: valueLongitude)
    geoCoder.reverseGeocodeLocation(newLocation, completionHandler: {(placemarks: [AnyObject]!, error: NSError!) in
        if error != nil {
            println("Geocode failed with error: \(error.localizedDescription)")
        }
        if placemarks.count > 0 {
            let placemark   = placemarks[0] as! CLPlacemark
            let addressDictionary = placemark.addressDictionary
            let address     = addressDictionary[kABPersonAddressStreetKey] as! NSString
            let city        = addressDictionary[kABPersonAddressCityKey] as! NSString
            let state       = addressDictionary[kABPersonAddressStateKey] as! NSString
            let postcode    = addressDictionary[kABPersonAddressZIPKey] as! NSString
            let country     = addressDictionary[kABPersonAddressCountryKey] as! NSString

            println("\(address) \(city) \(state) \(postcode) \(country)") }
    })
1

There are 1 answers

3
The Tom On BEST ANSWER

Your problem is most likely due to the fact that reverseGeocodeLocation is an asynchronous request made to Apple servers.

What needs to happen is:

  1. You call reverseGeocodeLocation
  2. reverseGeocodeLocation finishes, starts its completion which calls a method passing the placemark you just recovered.

In order to do that:

@IBAction func btnInsertClicked(sender: AnyObject) { 
    var locationRecord: LocationRecord = LocationRecord() 

    // Get Address Information 
    let geoCoder = CLGeocoder() 
    let newLocation = CLLocation(latitude: valueLatitude, longitude: valueLongitude) 
    geoCoder.reverseGeocodeLocation(newLocation, completionHandler:
        {(placemarks: [AnyObject]!, error: NSError!) in 
            if error != nil { 
                println("Geocode failed with error: (error.localizedDescription)") 
            }

            if placemarks.count > 0 { 
                let myPlacemark = placemarks[0] as! CLPlacemark 

                // Here call the method that uses myPlacemark
                self.myAwesomeMethod(placemarks[0] as! CLPlacemark)
            } else {
                println("No placemark")
            } 
        })
}

Where you need to use it in your code:

func myAwesomeMethod(placemark: CLPlacemark) {
    // Do stuff with placemark
}

I won't have my mac until tonight but if that doesn't work, leave a comment and we will work this out