【问题标题】:Phone numbers detected using NSDataDetector could not be opened using openURL使用 NSDataDetector 检测到的电话号码无法使用 openURL 打开
【发布时间】:2017-07-02 20:06:55
【问题描述】:

好的,我使用NSDataDetector 来检测这样的电话号码:

func matchesFor(type: NSTextCheckingResult.CheckingType) -> [String] {

    do {

        let nsstring = self as NSString
        let detector = try NSDataDetector(types: type.rawValue)
        let matches = detector.matches(in: self, options: [], range: NSRange(location: 0, length: nsstring.length))

        return matches.map { nsstring.substring(with: $0.range) }

    } catch {
        return []
    }
}

它会找到一个数字。但后来我尝试像这样打开这些数字:

func makeACall(phoneNumber: String) {

    if let url = URL(string: "tel://\(phoneNumber)"), UIApplication.shared.canOpenURL(url) {
        UIApplication.shared.openURL(url)
    }
}

它不起作用。为什么?

我的意思是:

+48 576-786-987

我应该用那个号码做任何事情来使用它来打电话吗?

【问题讨论】:

    标签: ios swift nsdatadetector


    【解决方案1】:

    删除空间,这应该工作: +48576-786-987

    【讨论】:

    • 谢谢,它可以工作...看起来 url 不接受空格:) 很明显:)
    【解决方案2】:

    作为Yun CHEN said, 空格是电话 URL 中的无效字符。

    如果您使用 URLComponents() 而不是 URL(string:) 那么所有 必要时字符会自动转义。示例:

    let phoneNumber = "+48 576-786-987"
    
    var urlcomps = URLComponents()
    urlcomps.scheme = "tel"
    urlcomps.host = phoneNumber
    
    if let url = urlcomps.url, UIApplication.shared.canOpenURL(url) {
        print("Calling:", url.absoluteString) // Calling: tel://+48%20576-786-987
        UIApplication.shared.openURL(url)
    }
    

    另请注意,NSTextCheckingResult 有一个可选的phoneNumber 属性,该属性在检测到电话号码时设置。所以 您可以将代码稍微简化为

    extension String {
        func phoneNumbers() -> [String] {
    
            let detector = try! NSDataDetector(types: NSTextCheckingResult.CheckingType.phoneNumber.rawValue)
            let matches = detector.matches(in: self, range: NSRange(location: 0, length: utf16.count))
            return matches.flatMap { $0.phoneNumber }
        }
    }
    

    NSDataDetector(types:) 只能因无效类型而失败,即 编程错误。因此在这里强制尝试是可以接受的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-12-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-27
      • 1970-01-01
      相关资源
      最近更新 更多