2017-07-02 90 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:)只能失敗無效的類型,這將是一個 編程錯誤。因此,強制嘗試在這裏是可以接受的。