接受一个NSURL的String初始化程序是可失败的,文档中说:
如果URL字符串格式错误,则返回零。
试图使用NSURL(string: "tel://+49 00 00 00 00 00")构造URL返回为零。
stringByAddingPercentEscapesUsingEncoding(_:)和朋友们在iOS 9中反对stringByAddingPercentEncodingWithAllowedCharacters(_:),因为stringByAddingPercentEncodingWithAllowedCharacters(_:)需要一个NSCharacterSet。哪个NSCharacterSet描述了tel: URL中有效的字符?
都不是
URLFragmentAllowedCharacterSet()URLHostAllowedCharacterSet()URLPasswordAllowedCharacterSet()URLPathAllowedCharacterSet()URLQueryAllowedCharacterSet()URLUserAllowedCharacterSet()..。似乎是相关的
发布于 2016-03-09 11:36:50
您可以将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)
}https://stackoverflow.com/questions/35889628
复制相似问题