How to validate an url on the iPhone

Thizzer picture Thizzer · Sep 24, 2009 · Viewed 70.8k times · Source

In an iPhone app I am developing, there is a setting in which you can enter a URL, because of form & function this URL needs to be validated online as well as offline.

So far I haven't been able to find any method to validate the url, so the question is;

How do I validate an URL input on the iPhone (Objective-C) online as well as offline?

Answer

Vincent Guerci picture Vincent Guerci · Feb 22, 2011

Why not instead simply rely on Foundation.framework?

That does the job and does not require RegexKit :

NSURL *candidateURL = [NSURL URLWithString:candidate];
// WARNING > "test" is an URL according to RFCs, being just a path
// so you still should check scheme and all other NSURL attributes you need
if (candidateURL && candidateURL.scheme && candidateURL.host) {
  // candidate is a well-formed url with:
  //  - a scheme (like http://)
  //  - a host (like stackoverflow.com)
}

According to Apple documentation :

URLWithString: Creates and returns an NSURL object initialized with a provided string.

+ (id)URLWithString:(NSString *)URLString

Parameters

URLString : The string with which to initialize the NSURL object. Must conform to RFC 2396. This method parses URLString according to RFCs 1738 and 1808.

Return Value

An NSURL object initialized with URLString. If the string was malformed, returns nil.