Vikas Singh Vikas Singh - 1 year ago 94
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.

Answer Source

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;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download