如何正确传递值到谷歌地图网址方案回调?

时间:2016-06-21 15:14:17

标签: ios swift google-maps google-maps-sdk-ios

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

  

致命错误:在解包可选值时意外发现nil

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

继承代码

 @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.")
        }

1 个答案:

答案 0 :(得分:2)

需要对NSURL的字符串进行编码才能创建有效的NSURL。基于此answer,你应该做类似的事情:

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