To search for a place and return its latitude and longitude in Swift, we can use Apple's MapKit framework and its CLGeocoder class.
First, we need to import the MapKit framework into our project:
main.swift14 chars2 lines
Then, we need to create an instance of the CLGeocoder class and use its geocodeAddressString method to search for the place's location:
main.swift528 chars18 lines
In this example, we are searching for "New York" and handling possible errors that may occur during the geocoding process. If the search is successful, we are retrieving the first placemark returned by the geocoder and extracting its location's latitude and longitude coordinates.
We can replace "New York" with any other place name or address. Keep in mind that the geocoder may not always return accurate results, especially for less specific search queries.
gistlibby LogSnag