2017-07-02 69 views
0

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

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 

我应该做任何与该号码以呼叫使用它?

回答

2

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

+0

谢谢,它的工作原理...它看起来像url不接受空间:)什么是显而易见的:) –

+0

不客气! :) –

2

由于Yun CHEN said, 空间是在手机网址无效字符。

如果您使用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:)只能失败无效的类型,这将是一个 编程错误。因此,强制尝试在这里是可以接受的。