Vikas Singh Vikas Singh - 8 months ago 41
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:

NSURL *url = [NSURL URLWithString:@""];

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.


This works:

NSURL *url = [NSURL URLWithString:@""]; 
NSString *webData= [NSString stringWithContentsOfURL:url]; 

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;