我有一些按钮,当按下这些按钮时,它们会从数组中调用/发送消息。即 button1 将调用数组索引 0 处的数字,button2 调用索引 1 处的数字,等等。出于某种原因,每当数组中的数字包含 xxx-xxx-xxx 以外的格式时,它就会崩溃(即 (xxx) xxx-xxx ).然而,即使数组不是零,日志也会给我以下错误:
有人知道为什么会这样吗? 这是一切的代码:
import UIKit
import AddressBook
var contactInfo: [String] = []
[...]
override func viewDidLoad() {
super.viewDidLoad()
//this is the function that grabs the array from an app group
setUpCallMessageButtons()
[...]
callButton1.addTarget(self, action: "call:", forControlEvents: UIControlEvents.TouchUpInside)
}
func call(sender:UIButton!)
{
if (sender == callButton1) {
println("\(contactInfo)")
var url:NSURL? = NSURL(string: "tel:\(contactInfo[0])")
self.extensionContext?.openURL(url!, completionHandler:{(success: Bool) -> Void in
})
}
}
func setUpCallMessageButtons(){
let appGroupID = "**redacted**"
let defaults = NSUserDefaults(suiteName: appGroupID)
contactInfo = (defaults!.objectForKey("contactInfo") as! [String])
println("\(contactInfo)")
//This is gives the log down below. As you can see, none are nil.
}
按钮 1、2 和 5 工作,而 3 和 4 总是崩溃。
最佳答案
我的猜测是,如果电话号码的格式不正确,将其转换为 NSURL 的调用将失败并返回 nil。
您可能需要将对 openURL 的调用包装在一个可选的绑定(bind)(“if let”) block 中:
var url:NSURL? = NSURL(string: "tel:\(contactInfo[0])")
if let url = url
{
self.extensionContext?.openURL(url!,
completionHandler:
{
(success: Bool) -> Void in
}
}
else
{
println("Phone number \(contactInfo[0]) is not in a valid format")
}
在尝试创建 URL 之前,您可能希望去掉电话号码中的括号。一种简单的方法是使用 NSString 方法 stringByReplacingOccurrencesOfString:withString:
。
关于ios - 调用/消息代码崩溃?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29923788/