我使用Swift构建了一个简单的iOS应用程序并尝试创建一个允许用户拨打预配置号码的按钮。
以下是我目前使用的代码,从我以前的文档中可以看出这些代码是正确的,但Xcode显示错误:
在其自己的初始值'
中使用的变量
显示错误的行是我试图调用UIApplication时。
@IBAction func contact_number_button(_ sender: AnyObject) {
let contact_number = "XXXXXXXXXXXXXX"
let phoneURL = NSURL(string: "tel://\(contact_number)") {
UIApplication.sharedApplication().openURL(phoneURL)
}
答案 0 :(得分:1)
if let phoneCallURL:NSURL = NSURL(string:"tel://\(contact_number)") {
let application:UIApplication = UIApplication.sharedApplication()
if (application.canOpenURL(phoneCallURL)) {
application.openURL(phoneCallURL);
}
}
答案 1 :(得分:0)
您应该以这种方式检查phoneURL
是否可用:
if let phoneURL = NSURL(string: "tel://\(contact_number)") {
UIApplication.sharedApplication().openURL(phoneURL)
}
尝试查看Optional Chaining as an Alternative to Forced Unwrapping
答案 2 :(得分:0)
第二版有一个好的做法:
@IBAction func contact_number_button(_ sender: AnyObject) {
let contact_number = "XXXXXXXXXXXXXX"
if let phoneURL = NSURL(string: "tel://\(contact_number)") {
UIApplication.sharedApplication().openURL(phoneURL)
}
}
版本打开可选项:
我相信你遇到的问题是打开支撑,试试这个:
@IBAction func contact_number_button(_ sender: AnyObject) {
let contact_number = "XXXXXXXXXXXXXX"
let phoneURL = NSURL(string: "tel://\(contact_number)")
UIApplication.sharedApplication().openURL(phoneURL!)
}
答案 3 :(得分:0)
非常感谢您的帮助!
这里的所有答案都让我找到了解决方案。我想我已经选错了一周开始自学编写Swift代码并一起编码! XCode 8.0一直告诉我iOS10中的某些命令已被折旧,其中一个是openURL命令。下面的代码现在允许我使用我的iPhone 6S(iOS 10)对预配置的号码进行工作调用。 XCode仍然告诉我命令openURL已被折旧,但它正在运行。如果以下不正确或有更好的方法,请随时纠正!非常感谢你们!这是我的第一篇文章,你的支持令人惊叹!
@IBAction func contact_number_button(_ sender: AnyObject) {
let contact_number = "XXXXXXXXXXXXXXX"
if let phoneURL = NSURL(string: "tel://\(contact_number)"){
UIApplication.shared.openURL(phoneURL as URL)
}
}