The NSURL
initializer that takes a String
is failable, and the documentation says:
If the URL string was malformed, returns nil.
Attempting to construct a URL with NSURL(string: "tel://+49 00 00 00 00 00")
returns nil.
stringByAddingPercentEscapesUsingEncoding(_:)
and friends are deprecated in iOS 9 in favour of stringByAddingPercentEncodingWithAllowedCharacters(_:)
, which takes an NSCharacterSet
. Which NSCharacterSet
describes the characters which are valid in a tel:
URL?
None of
URLFragmentAllowedCharacterSet()
URLHostAllowedCharacterSet()
URLPasswordAllowedCharacterSet()
URLPathAllowedCharacterSet()
URLQueryAllowedCharacterSet()
URLUserAllowedCharacterSet()
... seem to be relevant
You can NSDataDetector class to grep phone number from string. Next step in to remove all unnecessary characters from detected number and create 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
}
Example:
let possibleNumber = "+49 00 00 00 00 00"
if let number = getPhoneNumber(possibleNumber), let url = NSURL(string: "tel://\(number)") {
print(url.absoluteString)
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.