2

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

Robert Atkins
  • 23,528
  • 15
  • 68
  • 97

1 Answers1

0

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)
 }
salabaha
  • 2,468
  • 1
  • 17
  • 18
  • We're specifying the list of phone numbers from code ourselves, so we don't have to extract them from free text (but that's an interesting pointer.) Also a leading `+` is a valid character in a phone number so I don't think we want to strip that out, which your code will do. – Robert Atkins Mar 09 '16 at 11:52
  • NSDataDetector use reg exp to get phone numbers from string. Its a good way to validate that strings you have actually contains phone numbers. But you can just ignore getPhoneNumber fund if you sure your phone numbers are correct. Is such case you need to use convertStringToNumber func with small modification. Like before trimming non digit characters check if "+" sine exist and if so add to the beginning on string before returning result. – salabaha Mar 09 '16 at 12:27