I have a function locationManager that prints out zipCode but everytime I change this function to return a String or implement a completion block, the postal code no longer gets assigned a value. Can someone show how to make this function return a zipCode. I think I have to use async or Concurrency not sure though
import CoreLocation
import CoreLocationUI
class locationManager: NSObject, ObservableObject, CLLocationManagerDelegate {
@Published var location: CLLocationCoordinate2D?
let manager = CLLocationManager()
let geocoder = CLGeocoder()
override init() {
super.init()
manager.delegate = self
manager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
manager.startUpdatingLocation()
}
func requestLocation() {
manager.requestAlwaysAuthorization()
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
guard let location = locations.last else { return }
geocoder.reverseGeocodeLocation(location) { (placemarks, error) in
if error == nil {
if let placemark = placemarks?.first {
if let postalCode = placemark.postalCode {
print(postalCode)
}
}
}
}
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
print("Error getting location: \(error)")
}
func status(){
switch manager.authorizationStatus {
case .authorizedWhenInUse:
print("")
case .authorizedAlways:
locationManager(CLLocationManager(), didUpdateLocations: [CLLocation()])
case .denied:
print("")
case .notDetermined:
print("")
case .restricted:
print("")
@unknown default:
print("")
}
}
}