Reputation: 1608
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.")
}
Upvotes: 0
Views: 672
Reputation: 10296
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.")
}
Upvotes: 2