Search code examples
iosswiftsafarimkmapview

How to prevent Safari from launching when using MapLinks?


I am using the following code to launch Maps from within my project:

@IBAction func navigate(){

        let mapLinksSchemeURL = URL(string: "http://maps.apple.com/?daddr=\(latitude),\(longitude)&t=s&dirflg=d")

        UIApplication.shared.open(mapLinksSchemeURL!, options: [:], completionHandler: nil)
    }

This code launches Safari first then it continues to launch Maps. This doesn't particularly look very refined. Is there a way to skip Safari and go straight to Maps?


Solution

  • You have an URL that´s why it goes to Safari before it recognises the type and goes to Apple Maps.

    Use the following code instead to go straight to Apple Maps:

    let regionDistance:CLLocationDistance = 10000
    let coordinates = CLLocationCoordinate2DMake(latitude, longitude)
    let regionSpan = MKCoordinateRegionMakeWithDistance(coordinates, regionDistance, regionDistance)
    let options = [
        MKLaunchOptionsMapCenterKey: NSValue(mkCoordinate: regionSpan.center),
        MKLaunchOptionsMapSpanKey: NSValue(mkCoordinateSpan: regionSpan.span)
    ]
    let placemark = MKPlacemark(coordinate: coordinates, addressDictionary: nil)
    
    let mapItem = MKMapItem(placemark: placemark)
    mapItem.name = "Start"
    mapItem.openInMaps(launchOptions: options)