NSURL
的{{1}}初始化程序可以使用,文档说:
如果网址字符串格式错误,则返回nil。
尝试构建一个String
的网址,返回nil。
NSURL(string: "tel://+49 00 00 00 00 00")
和朋友在iOS 9中被弃用,而stringByAddingPercentEscapesUsingEncoding(_:)
则需要stringByAddingPercentEncodingWithAllowedCharacters(_:)
。哪个NSCharacterSet
描述了NSCharacterSet
网址中有效的字符?
没有
tel:
URLFragmentAllowedCharacterSet()
URLHostAllowedCharacterSet()
URLPasswordAllowedCharacterSet()
URLPathAllowedCharacterSet()
URLQueryAllowedCharacterSet()
......似乎是相关的
答案 0 :(得分:0)
您可以 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)
}