0

好的,我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

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

4

2 回答 2

2

删除空格,这应该可以:+48576-786-987

于 2017-07-02T09:22:27.107 回答
2

正如Yun CHEN 所说,空格是电话 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:)只能因无效类型而失败,这将是编程错误。因此,强制尝试在这里是可以接受的。

于 2017-07-02T09:57:23.087 回答