0

I am using swift 2.0, XCode 7.2 and deployment target is 9.2. On button click I wish to redirect to apple maps to show a location. Following is my code which is not working:

var addr = self.sortedDict.valueForKey("ADDRESS1").objectAtIndex(cellIndexPath!.row).objectAtIndex(0) as! String + "," + (self.sortedDict.valueForKey("CITY").objectAtIndex(cellIndexPath!.row).objectAtIndex(0) as! String) + "," + (self.sortedDict.valueForKey("STATE").objectAtIndex(cellIndexPath!.row).objectAtIndex(0) as! String)
    let strUrl: String = "http://maps.apple.com?address=" + addr
    let url: NSURL = NSURL(string: strUrl.stringByAddingPercentEncodingWithAllowedCharacters(.URLHostAllowedCharacterSet())!)!

    if UIApplication.sharedApplication().canOpenURL(url) {
        UIApplication.sharedApplication().openURL(url)
    } else {
        print(UIApplication.sharedApplication().canOpenURL(url))
    }

Error I get is:

    -canOpenURL: failed for URL: "http%3A%2F%2Fmaps.apple.com%3Faddress=4702%20Katy%20Hockley%20Cut%20Off%20Rd,Katy,TX" - error: "Invalid input URL"
false

In iOS 9 you must whitelist any URL schemes your App wants to query in Info.plist under the LSApplicationQueriesSchemes key.

What key should I specify for apple maps?

z22
  • 10,013
  • 17
  • 70
  • 126
  • http://stackoverflow.com/questions/21983559/opens-apple-maps-app-from-ios-app-with-directions – Uma Madhavi Dec 18 '15 at 11:41
  • Apple maps can't be removed, so why bother checking `canOpen` - just open the URL – Paulw11 Dec 18 '15 at 12:28
  • your URL is basically invalid, make it valid, then it will work. hint: _don't percentage-encode the parts of the URL which must not be encoded at all_. – holex Dec 18 '15 at 12:33

1 Answers1

1

You can use MKMapItem to open apple map directly, instead of opening a URL

//your address to be opened
let address: String = "4702 Katy Hockley Cut Off Rd,Katy,TX"
let geocoder: CLGeocoder = CLGeocoder()
// Get place marks for the address to be opened
geocoder.geocodeAddressString(address, completionHandler: {(placemarks: [CLPlacemark]?, error: NSError?) -> Void in
    if (placemarks?.count > 0) {
        if let placemark = placemarks?.first {
            let mkPlacemark  = MKPlacemark(placemark: placemark)

            //Create map item and open in map app 
            let item = MKMapItem(placemark: mkPlacemark)
            item.name = address
            item.openInMapsWithLaunchOptions(nil)
        }

    }
})
Johnykutty
  • 12,091
  • 13
  • 59
  • 100