How to get the source code of a URL

12,748

Solution 1

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;

Solution 2

The simple version:

NSURL *TheUrl = [NSURL URLWithString:@"http://google.com"];

NSString *webData = [NSString stringWithContentsOfURL:TheUrl 
                              encoding:NSASCIIStringEncoding
                              error:nil];

NSLog(@"%@", webData);

Solution 3

You can get the data in following ways :-

1 .Using NSUrlConnection as asynchronous reuest

2. Synchronous NSUrlConnection

NSURL *URL = [NSURL URLwithString:@"http://www.google.com"]; 
NSURLRequest *request = [NSURLRequest requestWithURL:URL]; 
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil]; 

Simply to check
NSURL *URL = [NSURL URLwithString:@"http://google.com"]; 
NSString *webData= [NSString stringWithContentsOfURL:URL]; 

Solution 4

Simple async solution with GCD:

- (void)htmlFromUrl:(NSString *)url handler:(void (^)(NSString *html, NSError *error))handler
{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void){
        NSError *error;
        NSString *html = [NSString stringWithContentsOfURL:[NSURL URLWithString:url] encoding:NSASCIIStringEncoding error:&error];
        dispatch_async(dispatch_get_main_queue(), ^(void){
            if (handler)
                handler(html, error);
        });
    });
}

then

[self htmlFromUrl:@"http://stackoverflow.com" handler:^(NSString *html, NSError *error) {
    NSLog(@"ERROR: %@ HTML: %@", error, html);
}];
Share:
12,748
Vikas Singh
Author by

Vikas Singh

Entrepreneur | Innovator | Human

Updated on June 13, 2022

Comments

  • Vikas Singh
    Vikas Singh almost 2 years

    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.

  • Vikas Singh
    Vikas Singh almost 12 years
    Sorry that was a typo. I have updated the question. There are no syntax errors in the code
  • fbernardo
    fbernardo almost 12 years
    @sanjana Google is redirecting, let me best a little bit more.