Vikas Singh Vikas Singh - 5 months ago 21
iOS Question

How to get the source code of a URL

I am not able to get the HTML source code when I try to request this URL: http://www.google.co.in/search?q=search

NSURL *url = [NSURL URLWithString:@"http://www.google.co.in/search?q=search"];

NSMutableURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
NSData *data = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:nil error:nil];
NSLog(@"Webdata : %@", [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);


The data is always NULL.

Answer

This works:

NSURL *url = [NSURL URLWithString:@"http://www.google.co.in/search?q=search"]; 
NSString *webData= [NSString stringWithContentsOfURL:url]; 
NSLog(@"%@",webData);

But if you need to use a NSURLConnection you should use it asynchronously and implement the willSendRequest method to handle redirection.

- (NSURLRequest *)connection:(NSURLConnection *)connection willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response;