如何正确地将值传递给 google 映射 url 方案回调?

How to properly pass a value to google maps url scheme callback?

每当我尝试 运行 代码时,总是显示

之类的错误

fatal error: unexpectedly found nil while unwrapping an Optional value

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

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