【问题标题】:NSURL for telephone always nil电话的 NSURL 总是为零
【发布时间】:2016-02-14 12:48:28
【问题描述】:

这是我的NSURL

let url = NSURL(string: "tel://\(phoneCall)")

它始终是nil,尽管phoneCall 是一个有效的手机号码字符串,而且我正在真实的iPhone 上进行测试。

我试过了

let url = NSURL(string: "tel:\(phoneCall)")

但它仍然是nil

【问题讨论】:

  • 我做了检查,代码在Xcode7.1中运行正常。让 url = NSURL(string: "tel://("0123456789")") 如果让 url = url { print(url) }
  • let url = NSURL(string: "tel://123456789") 在 Xcode 7.1 上对我来说不是 nil
  • 为了方便调试使用两个语句:第一个创建字符串,第二个从字符串创建 URL。这样你就可以准确地看到字符串是什么。
  • 省略斜线 - 电话:号码
  • 你的“phoneCall”还有空格吗?

标签: ios iphone swift nsurl


【解决方案1】:
let phoneCall = "tel://9000002143";
let url:NSURL = NSURL(string:phoneCall);
    //OR
var url:NSURL = NSURL(string: "tel://9000002143")
if phoneCall == nil || phoneCall.isEmpty 
{
   print("phoneCall is empty or nil.")
}
else
{
  UIApplication.sharedApplication().openURL(url);
}

【讨论】:

  • 在 Swift 中 "tel://\(phoneCall)" 使用字符串插值。它将使用“phoneCall”变量创建正确的代码。
【解决方案2】:

phoneCall 设置在哪里?

我在可选类型方面遇到了类似的问题。这段代码说明了问题:

let user = row.value
let phone = user?.phone
let url = NSURL(string: "tel://\(phone)")
UIApplication.sharedApplication().openURL(url!)

本例中urlString变量的值为"tel://Optional(\"11XXXXXXXXX\")",因为user变量可以为nil。

您必须首先确保 user 不为零,例如:

guard let user = row.value else {
    return
}
let phone = user.phone
let urlString = "tel://\(phone)"
let url = NSURL(string: urlString)
UIApplication.sharedApplication().openURL(url!)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-02-14
    • 2015-09-02
    • 1970-01-01
    • 1970-01-01
    • 2014-11-15
    • 2016-11-24
    • 2012-03-12
    相关资源
    最近更新 更多