每当我尝试运行代码时,总是会显示错误,例如
致命错误:在解包可选值时意外发现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.")
}
答案 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.")
}