Tuesday, 9 October 2012

Validate and Parse NSURL in Objective C


I need to check if Url is valid or not in my iPhone application so i found below snippet from  


We can validate a url by simply using Foundation Framework as follows: 

        NSURL *myURL = [NSURL URLWithString:@"http://google.com"];
        if (myURL && myURL.scheme && myURL.host) {
            NSLog(@"URL is validated");
        } else {
            UIAlertView *alertMsg = [[UIAlertView alloc] initWithTitle:@"Error" 
                                     message:@"URL is invalid" delegate:nil 
                                     cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
            [alertMsg show];
            [alertMsg release];
        }


Output: 
URL is validated


Above can be achieved using RegexKit also as follows:

    NSString *regexExpression = @"(http|https)://((\\w)*|([0-9]*)|([-|_])*)+([\\.|/]((\\w)*|([0-9]*)|([-|_])*))+";
    NSString *urlString = @"http://google.com";
    
    NSString *matchedString = [urlString stringByMatching:regexExpression];

if you want to validate url string like: www.google.com just replace
(http|https):// with ((http|https)://)* 

You can download RegexKit from 
http://regexkit.sourceforge.net/


Some time we need to parse a NSURL and fetch a particular part out from it.
We can parse a NSURL as follows:

            NSURL *url = [NSURL URLWithString:@"https://www.google.co.in/search?q=validate+url+objective+c&oq=validate+url+objective+c&sugexp=chrome,mod=6&sourceid=chrome&ie=UTF-8"];

            NSLog(@"URL Scheme: %@", [url scheme]); 
            NSLog(@"URL Host: %@", [url host]); 
            NSLog(@"URL Port: %@", [url port]);     
            NSLog(@"URL Path: %@", [url path]);     
            NSLog(@"URL Relative path: %@", [url relativePath]);
            NSLog(@"URL Path components as array: %@", [url pathComponents]);        
            NSLog(@"URL Parameter string: %@", [url parameterString]);   
            NSLog(@"URL Query: %@", [url query]);       
            NSLog(@"URL Fragment: %@", [url fragment]);


Output:
 Scheme: https
 Host: www.google.co.in
 Port: (null)
 Path: /search
 Relative path: /search
 Path components as array: (
    "/",
    search
)
 Parameter string: (null)
 Query: q=validate+url+objective+c&oq=validate+url+objective+c&sugexp=chrome,mod=6&sourceid=chrome&ie=UTF-8
 Fragment: (null)











1 comment:

  1. This actually does not work if you use URLWithstring..
    it just checks if you have stuff there..

    try using htp://google.com it will pass as a good URL

    ReplyDelete