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.
You can use the URLConstructor to check if a string is a valid URL. URLConstructor ( new URL(url) ) returns a newly created URL object defined by the URL parameters. A JavaScript TypeError exception is thrown if the given URL is not valid.
If it's an NSString, you find the length like this: int len = [myString length]; But it will be different if your string is not an NSString. Save this answer.
Alternatively, we can check if a string is a URL using a regular expression. We do this by calling the test() method on a RegExp object with a pattern that matches a string that is a valid URL. The RegExp test() method searches for a match between a regular expression and a string. It returns true if it finds a match.
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"]
.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With