I'm a newbie in Swift and I need to set var postalCode
in viewDidLoad()
. As you can see on my code below, I used the reverse geocode location in didUpdateLocations
but since it's asynchronous, the postalCode
variable is not set in viewDidLoad()
. How can I do this?
ViewController.swift
import UIKit
import CoreLocation
class ViewController: UIViewController, CLLocationManagerDelegate {
let locationManager = CLLocationManager()
var postalCode = ""
override func viewDidLoad() {
super.viewDidLoad()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestWhenInUseAuthorization()
locationManager.startUpdatingLocation()
println("Postal code is: \(self.postalCode)")
}
func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
CLGeocoder().reverseGeocodeLocation(manager.location, completionHandler: {(placemarks, error)-> Void in
if error != nil {
println("Reverse geocoder failed with error: \(error.localizedDescription)")
return
}
if placemarks.count > 0 {
let placemark = placemarks[0] as! CLPlacemark
self.locationManager.stopUpdatingLocation()
self.postalCode = (placemark.postalCode != nil) ? placemark.postalCode : ""
println("Postal code updated to: \(self.postalCode)")
}else{
println("No placemarks found.")
}
})
}
func locationManager(manager: CLLocationManager!, didFailWithError error: NSError!) {
println("Location manager error: \(error.localizedDescription)")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}