如何将值正确传递给Google Maps URL方案回调



每当我尝试运行代码时,总是显示错误,例如

致命错误:未包装可选值

时出乎意料地发现了无效

firstAddress值是 450 Serra Mall, Stanford, CA 94305, United States

Heres代码

 @IBAction func locationOneTapped(sender: UIButton) {
        let testURL: NSURL = NSURL(string: "comgooglemaps-x-callback://")!
        if UIApplication.sharedApplication().canOpenURL(testURL) {
            if let address = firstAddress {
                let directionsRequest: String = "comgooglemaps-x-callback://" + "?daddr=(address)" + "&x-success=sourceapp://?resume=true&x-source=AirApp"
                let directionsURL: NSURL = NSURL(string: directionsRequest)!
                UIApplication.sharedApplication().openURL(directionsURL)
            }
        }
        else {
            NSLog("Can't use comgooglemaps-x-callback:// on this device.")
        }

nsurl的字符串需要编码以创建有效的nsurl。基于此答案,您应该做类似的事情:

let testURL: NSURL = NSURL(string: "comgooglemaps-x-callback://")!
if UIApplication.sharedApplication().canOpenURL(testURL) {
   if let address = firstAddress?.stringByAddingPercentEncodingWithAllowedCharacters(.URLHostAllowedCharacterSet()) {
      let directionsRequest: String = "comgooglemaps-x-callback://" + "?daddr=(address)" + "&x-success=sourceapp://?resume=true&x-source=AirApp"
      let directionsURL: NSURL = NSURL(string: directionsRequest)!
      UIApplication.sharedApplication().openURL(directionsURL)
   }
}
else {
   NSLog("Can't use comgooglemaps-x-callback:// on this device.")
}

最新更新