15

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.

3 Answers 3

37

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.

UPDATE

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 && url.host)
{
   //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"].

Sign up to request clarification or add additional context in comments.

7 Comments

Thanks for pointing me in the right direction :) Got it sorted now, need a lot more practice with Objective C though! haha
It seems to have a loose definition what's a valid URL. "foo.com" will parse so you probably want to check that the resulting object has a scheme property.
you can't just trust URLWithString, because NSURL *url = [NSURL URLWithString:@"a"]; will return a to you. see stackoverflow.com/questions/1471201/…
However, you can use this if you want to use regex instead.
I mean this " you can just check the return value to determine if the URL is valid." statement is not enough.
|
3

Here is an alternative solution which I came across. You can do like this.

NSURLRequest *req = [NSURLRequest requestWithURL:[NSURL URLWithString:@"yourstring"]];
bool valid = [NSURLConnection canHandleRequest:req];

Source : https://stackoverflow.com/a/13650542/2513947

Comments

-1

You can look at below code to check whether a string contains website url or simple text.

 NSString *getString =[[NSUserDefaults standardUserDefaults]valueForKey:@"searchKey"];
    if([getString rangeOfString:@"Www"].location == NSNotFound
       && [getString rangeOfString:@"www"].location == NSNotFound && [getString rangeOfString:@"com"].location == NSNotFound)
    {
        [companyNameTF setText:[[NSUserDefaults standardUserDefaults]valueForKey:@"searchKey"]];
    }
    else
    {
         [websiteTF setText:[[NSUserDefaults standardUserDefaults]valueForKey:@"searchKey"]];
    }

1 Comment

This works in very limited cases. I.e. only urls that include www and com, which is by no means all of them. It only works if you know what to expect the URL to look like.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.