0

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.")
        }
airsoftFreak
  • 1,450
  • 5
  • 34
  • 64

1 Answers1

2

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.")
}
Community
  • 1
  • 1
Zell B.
  • 10,266
  • 3
  • 40
  • 49