Search code examples
iosswiftgoogle-mapsgoogle-maps-sdk-ios

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


Whenever I try run code, always shows error such as

fatal error: unexpectedly found nil while unwrapping an Optional value

firstAddress value is 450 Serra Mall, Stanford, CA 94305, United States

Heres the code

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

Solution

  • NSURL's string need to be encoded in order to create a valid NSURL. Based on this answer you should do something similar like this:

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