z22
z22

Reputation: 10083

iOS 9 redirect to apple map from app

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?

Upvotes: 0

Views: 1498

Answers (1)

Johnykutty
Johnykutty

Reputation: 12829

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)
        }

    }
})

Upvotes: 1

Related Questions