Search code examples
ioshttpnsurlnsdatadetector

iOS - NSDataDetector: Why does url missing '.com' (http://google) return as valid URL?


I am trying to validate provided URLs from a text field using NSDataDetector and it always returns valid if I enter a URL containing "http://" in the front of any text.

i.e. http://someurl, http://someotherurl, etc.

FYI - Although web browsers are capable of interpretting urls using the above format, NSURL returns an error when using this format every time. Since I need to call an action with a provided URL in my app, it needs to be valid when creating an NSURL from the provided URL text.

Any ideas on how to correct this as those urls are not really valid?

Here is my code:

   linkDetector = NSDataDetector(types: NSTextCheckingType.Link.rawValue, error: nil)
    linkDetector?.enumerateMatchesInString(self.textField.text, options: NSMatchingOptions(0), range: NSMakeRange(0, countElements(urlString!)), usingBlock: { (result: NSTextCheckingResult!, flags, stop) -> Void in
            self.validatedUrlString = self.textField.text
    })

Solution

  • Because there are new top level domains like .google and .apple so a URL consisting of just "apple" could actually be a valid URL these days.

    And in fact, if I type in http://apple, that plain looking valid URL actually successfully resolves in Firefox.