Xcode 14, Swift 5.7
CLLocationCoordinate2D is causing problem in Xcode 14. if you runt the following code in a new playground or in a Xcode 14 project:
import CoreLocation
print("Before")
let center = CLLocationCoordinate2D()
print("After")
This will immediately crash playground or halt your code due to this error:
libc++abi: terminating with uncaught exception of type NSException
I have example this working on Xcode 14.0 SwiftUI project and Playground by using CLLocation and not CLLocationCoordinate2D:
import CoreLocation
func getTimeZone(location: CLLocation, completion: @escaping ((TimeZone) -> Void)) {
let geocoder = CLGeocoder()
geocoder.reverseGeocodeLocation(location, completionHandler: { (placemarks, error) in
if error != nil {
print("reverse geodcode fail: \(String(describing: error))")
} else if let placemarks = placemarks, let pm = placemarks.first {
if let val = pm.timeZone {
completion(val)
}
}
})
}
getTimeZone(location: CLLocation(latitude: 42.48001070918, longitude: -76.4511703657)) { timeZone in
print("My Time zone: \(timeZone.identifier)")
}
Output:
My Time zone: America/New_York
Here's a variation (based on a modified answer for this post: Running reverseGeocodeLocation function create exception in SwiftPlay or return nothing) if you want to look up latitude and longitude using string and return all the other information from the location:
import CoreLocation
func getAddressFromLatLon(pdblLatitude: String, withLongitude pdblLongitude: String) {
guard let lat = Double(pdblLatitude),
let lon = Double(pdblLongitude) else { return }
let loc = CLLocation(latitude: lat, longitude: lon)
let ceo = CLGeocoder()
ceo.reverseGeocodeLocation(loc, completionHandler: { (placemarks, error) in
if error != nil {
print("reverse geodcode fail: \(String(describing: error))")
} else if let placemarks = placemarks, let pm = placemarks.first {
var addressString = ""
if let val = pm.subLocality {
addressString += val + ", "
}
if let val = pm.thoroughfare {
addressString += val + ", "
}
if let val = pm.locality {
addressString += val + ", "
}
if let val = pm.country {
addressString += val + ", "
}
if let val = pm.postalCode {
addressString += val + " "
}
print(addressString)
}
})
}
getAddressFromLatLon(pdblLatitude: "42.48001070918", withLongitude: "-76.4511703657")
Output:
Sapsucker Woods Rd, Lansing, United States, 14850