Reputation: 57
I am trying to get directions from any annotations that are found on my map. I am using CloudKit
as a database to store all my user's information. The annotations use the location
index in CloudKit
to map out their location on the map. Every time I run my code the annotation comes back as nil, how do I get my code to recognize the location from the annotation and return directions from apple maps?
@IBAction func getDirections(_ sender: Any) {
let view = MKPointAnnotation().coordinate
print("Annotation: \(String(describing: view ))")
let currentLocMapItem = MKMapItem.forCurrentLocation()
let selectedPlacemark = MKPlacemark(coordinate: view, addressDictionary: nil)
let selectedMapItem = MKMapItem(placemark: selectedPlacemark)
let mapItems = [selectedMapItem, currentLocMapItem]
let launchOptions = [MKLaunchOptionsDirectionsModeKey: MKLaunchOptionsDirectionsModeDriving]
MKMapItem.openMaps(with: mapItems, launchOptions:launchOptions)
}
Upvotes: 1
Views: 351
Reputation: 437372
There are two options:
You can use MKDirections
to get directions right in your app, without ever going to the Maps app.
You can also pass it off to the Maps app (like your above example) so that the user can then enjoy the full real-time navigation (see traffic, etc.).
But you don’t use the “open in Maps” API to return directions within your app. Use MKDirections
for that.
In your code snippet, you are doing:
let view = MKAnnotationView()
That creates an blank annotation view (with no annotation), so obviously if you try to get the annotation for it, it doesn't have one. You presumably want to either
MKMapViewDelegate
methods and use the annotation
for that annotation view on your map view; orBut don't try to create a new, blank annotation view and try to retrieve the annotation view for it, because it won't have one.
Upvotes: 1