Zachary Markham Zachary Markham - 5 months ago 14
Objective-C Question

How to determine if a string is a URL in Objective-C

I'm new to iPhone development and Objective-C. Using the ZBar SDK I've developed a basic app which scans a QR image from the photo album and outputs what it translates to.

I want to know if there is a way to take this output, determine whether it is a URL and if so open it in a web browser.



NSURL's URLWithString returns nil if the URL passed is not valid. So, you can just check the return value to determine if the URL is valid.


Just using URLWithString: will usually not be enough, you probably also want to check if the url has a scheme and a host, otherwise, urls such as al:/dsfhkgdsk will pass the test.

So you probably want to do something like this:

NSURL *url = [NSURL URLWithString:yourUrlString];
if (url && url.scheme &&
   //the url looks ok, do something with it
   NSLog(@"%@ is a valid URL", yourUrlString);

If you only want to accept http URLs you may want to add [url.scheme isEqualToString:@"http"].