I need to get the zipCode and city from multiple locations in my app so I created the following class.
import Foundation
import CoreLocation
class MyLocationManager: NSObject, CLLocationManagerDelegate {
private let locationManager = CLLocationManager()
private var zipCode:String?
private var city:String?
static let shared = MyLocationManager()
private override init() {
super.init()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.distanceFilter = kCLLocationAccuracyHundredMeters
locationManager.requestWhenInUseAuthorization()
locationManager.startUpdatingLocation()
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
CLGeocoder().reverseGeocodeLocation(manager.location!, completionHandler: {(placemarks, error)-> Void in
if error != nil {
//AlertView to show the ERROR message
}
if placemarks!.count > 0 {
let placemark = placemarks![0]
self.locationManager.stopUpdatingLocation()
self.zipCode = placemark.postalCode ?? ""
self.city = placemark.locality ?? ""
}else{
print("No placemarks found.")
}
})
}
public func getZipCode()->String {
return zipCode ?? ""
}
public func getCity()->String {
return city ?? ""
}
}
The issue is that the first time I call the getZipCode() or the getCity() methods I get an empty string. Here is how I'm using it in a viewController...
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
print("Location: \(MyLocationManager.shared.getCity())")// empty
}
/// Action to test it after viewDidLoad with a button
@IBAction func testing(_ sender: Any) {
print("Location: \(MyLocationManager.shared.getCity())")// returns the name of the city
}
}
In viewDidLoad I get an empty string but when I tap the testing button (second call) I do get the name of the city.
How can I make it update the city name in viewDidLoad as soon as I call MyLocationManager.shared.getCity()?