接受 String
的 NSURL
初始化器是可失败的,文档说:
If the URL string was malformed, returns nil.
尝试使用 NSURL(string: "tel://+49 00 00 00 00 00")
构建 URL 返回 nil。
stringByAddingPercentEscapesUsingEncoding(_:)
和 friend 在 iOS 9 中被弃用,取而代之的是 stringByAddingPercentEncodingWithAllowedCharacters(_:)
,它采用 NSCharacterSet
。哪个 NSCharacterSet
描述了 tel:
URL 中有效的字符?
没有
URLFragmentAllowedCharacterSet()
URLHostAllowedCharacterSet()
URLPasswordAllowedCharacterSet()
URLPathAllowedCharacterSet()
URLQueryAllowedCharacterSet()
URLUserAllowedCharacterSet()
...似乎是相关的
最佳答案
您可以使用 NSDataDetector 类从字符串中 grep 电话号码。下一步从检测到的数字中删除所有不必要的字符并创建 NSURL。
func getPhoneNumber(string: String) -> String? {
if let detector = try? NSDataDetector(types: NSTextCheckingType.PhoneNumber.rawValue) {
let matches = detector.matchesInString(string, options: [], range: NSMakeRange(0, string.characters.count))
if let string = matches.flatMap({ return $0.phoneNumber}).first {
let number = convertStringToNumber(string)
return number
}
}
return nil
}
func convertStringToNumber(var str: String) -> String {
let set = NSMutableCharacterSet()
set.formUnionWithCharacterSet(NSCharacterSet.whitespaceCharacterSet())
set.formUnionWithCharacterSet(NSCharacterSet.symbolCharacterSet())
set.formUnionWithCharacterSet(NSCharacterSet.punctuationCharacterSet())
str = str.componentsSeparatedByCharactersInSet(set).reduce(String(), combine: +)
return str
}
示例:
let possibleNumber = "+49 00 00 00 00 00"
if let number = getPhoneNumber(possibleNumber), let url = NSURL(string: "tel://\(number)") {
print(url.absoluteString)
}
关于ios - 哪个 NSCharacterSet 描述了在 tel : URL? 中有效的字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35889628/