我使用的是 swift 2.0、XCode 7.2,部署目标是 9.2。 单击按钮后,我希望重定向到苹果 map 以显示位置。以下是我的代码,但不起作用:
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))
}
我得到的错误是:
-canOpenURL: failed for URL: "http%3A%2F%2Fmaps.apple.com%3Faddress=4702%20Katy%20Hockley%20Cut%20Off%20Rd,Katy,TX" - error: "Invalid input URL"
false
在 iOS 9 中,您必须将您的应用程序想要在 Info.plist 中的 LSApplicationQueriesSchemes 键下查询的任何 URL 方案列入白名单。
我应该为苹果 map 指定什么键?
最佳答案
您可以使用MKMapItem直接打开苹果 map ,而不用打开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)
}
}
})
关于iOS 9 从应用程序重定向到苹果 map ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34354750/