无法使用openURL打开使用NSDataDetector检测到的电话号码

时间:2017-07-02 09:16:26

标签: ios swift nsdatadetector

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

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)
    }
}

我是否应该使用该号码进行任何操作才能拨打电话?

2 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分: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:)

/lib/modules/<VERSION>/extra/只能因无效类型而失败  编程错误。因此,强制尝试是可以接受的。