正在 Swift 打印但崩溃的调用

Make call in Swift printing but crashing

我正在使用 Factual 获取 phone 本地餐馆的数量,并为最终用户提供在我的应用程序中调用该地点的选项,但由于某些奇怪的原因它一直崩溃。

这是有效的代码:

   func tabBar(tabBar: UITabBar, didSelectItem item: UITabBarItem) {
        if item.tag == 1 {
            print("\(RestaurantCountry)")
        } 
    }

RestaurantCountry 表示电话号码phone。它在控制台中打印 phone 数字,但是当我使用此代码时它崩溃了。有人知道为什么会这样吗?

func tabBar(tabBar: UITabBar, didSelectItem item: UITabBarItem) {
    if item.tag == 1 {
        let url:NSURL = NSURL(string: "tel://\(RestaurantCountry)")!
        UIApplication.sharedApplication().openURL(url)
    } 
}

这段代码崩溃了,但我觉得它应该可以工作。谁能告诉我为什么会这样?

我删除了!这就是我得到的。不会让我用吧?

你需要正确解包可选的 url 来处理它是否为 nil。看来您还需要删除数字中的“-”。

let strippedUrlString = RestaurantCountry.stringByReplacingOccurrencesOfString("-", withString: "", options: NSStringCompareOptions.LiteralSearch, range: nil)

if let url = NSURL(string: "tel://\(strippedUrlString)") {
    UIApplication.sharedApplication().openURL(url)
} else {
    print("url is nil")
}

抛开对可选值的不安全处理(强制解包...),您需要确保 phone 数字的字符串表示具有以下 NSUrl query/attempt 发起呼叫。在这种情况下,我相信 phone 数字中的空格是失败查询的根源。

您可以使用 NSString 方法 stringByAddingPercentEncodingWithAllowedCharacters(_:) 对您的字符串进行编码,例如

let phoneNr : NSString = "(219) 465-4022"
let fixedPhoneNr = phoneNr
    .stringByAddingPercentEncodingWithAllowedCharacters(
        NSCharacterSet.URLQueryAllowedCharacterSet()) ?? "Non-encodable..."
print(fixedPhoneNr) // (219)%20465-4022

之后您应该(希望)能够(安全地)发起您的通话

if let phoneNumberURL = NSURL(string: "tel:\(fixedPhoneNr)") {
    UIApplication.sharedApplication().openURL(phoneNumberURL)
}

另请参阅: