Leave a rating/review
Notes: 18. Challenge: Find a Location
The student materials have been reviewed and are updated as of January, 2022.
In the last episode you learned how to do a reverse geocode lookup. That is, you had a CLLocation and you converted into an address. In most cases, like this challenge, you’ll be doing the opposite. That is, you’ll have an address and you’ll want to convert it to a CLLocation. That’s the object of this challenge.
Challenge
In the challenge files, download the playground from this project. Your challenge is to convert the address to CLLocation. You’ll need to create a CLGeocoder object and then call geocodeAddressString. Print the location to the console. Pause the video and give it a shot.
Solution
How’d that challenge go for you. I’ll walk you through the process. Open up the challenge playground for this challenge. You’ll see it already has an address in place. We need to create a geocoder object.
let geocoder = CLGeocoder()
Next we call the method geocodeAddressString passing in the location. This provides a closure of placemarks and an error object.
geocoder.geocodeAddressString(location) { placemarks, error in
}
Next we’ll check on any errors. If there is one, we’ll shut down with a fatal error.
if let error = error {
fatalError(error.localizedDescription)
}
Next, we’ll unwrap the placemark using a guard statement.
guard let placemark = placemarks?.first else {
return
}
Finally, we’ll print out the location that’s contained in the placemark.
print(placemark.location)
And that’s it. How’d that challenge go for you. If you got stuck, keep working through and you’ll be fine.