ios - 在 Swift 打印中调用电话但崩溃

标签 ios swift crash

我正在使用 Factual 来获取本地餐馆的电话号码,并让最终用户可以选择在我的应用程序中调用那个地方,但由于某些奇怪的原因它一直在崩溃。

这是有效的代码:

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

enter image description here

RestaurantCountry 代表电话号码。它在控制台中打印电话号码,但是当我使用此代码时它崩溃了。有人知道为什么会这样吗?
func tabBar(tabBar: UITabBar, didSelectItem item: UITabBarItem) {
    if item.tag == 1 {
        let url:NSURL = NSURL(string: "tel://\(RestaurantCountry)")!
        UIApplication.sharedApplication().openURL(url)
    } 
}

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

我删除!这就是我得到的。它不会让我用吗?
enter image description here

最佳答案

抛开对选项的不安全处理(强制展开...),您需要确保电话号码的字符串表示具有以下 NSUrl 的正确编码查询/尝试发起调用。在这种情况下,我相信电话号码中的空格是失败查询的根源。

您可以使用 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)
}

也可以看看:
  • Apple Url Scheme Reference - Phone links .
  • 关于ios - 在 Swift 打印中调用电话但崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36461528/

    相关文章:

    ios - 如何在 iOS iPhone 应用程序中对循环依赖项使用前向类声明?

    ios - Swift 4 GoogleMaps 添加 UIToolBar/make map "smaller"以适应其他 UI 元素

    ios - 如何在 Swift 中指示 for 循环的键是 NSString?

    ios - 如何使用 swift 解决 ViewController 之间的 segue 问题?

    swift - Firebase 按顺序获取数据

    ios - 应用程序在 UIPopoverPresentationController 中崩溃但没有显式弹出窗口?

    C++ 线程 - 崩溃

    ios - 从 Phonegap FaceBook 插件获取访问 token

    iphone - UINavigationController 包含一个 UITableView,然后是一个包含更多 UITableView 的 UITabBarController

    javascript - 在 IE 中打开后 html 索引元素崩溃