我正在使用 Factual 来获取本地餐馆的电话号码,并让最终用户可以选择在我的应用程序中调用那个地方,但由于某些奇怪的原因它一直在崩溃。
这是有效的代码:
func tabBar(tabBar: UITabBar, didSelectItem item: UITabBarItem) {
if item.tag == 1 {
print("\(RestaurantCountry)")
}
}
RestaurantCountry 代表电话号码。它在控制台中打印电话号码,但是当我使用此代码时它崩溃了。有人知道为什么会这样吗?
func tabBar(tabBar: UITabBar, didSelectItem item: UITabBarItem) {
if item.tag == 1 {
let url:NSURL = NSURL(string: "tel://\(RestaurantCountry)")!
UIApplication.sharedApplication().openURL(url)
}
}
这段代码崩溃了,但我觉得它应该可以工作。谁能告诉我为什么会这样?
我删除!这就是我得到的。它不会让我用吗?
最佳答案
抛开对选项的不安全处理(强制展开...),您需要确保电话号码的字符串表示具有以下 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)
}
也可以看看:
关于ios - 在 Swift 打印中调用电话但崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36461528/