DataWithContentsOfURL is not retrieving data

I am trying to get the source code for this page (http://www.sanmarinocard.sm) but dataWithContentsOfURL is not retrieving data.

NSURL *url = [NSURL URLWithString:@"http://www.sanmarinocard.sm"];
NSData *responseData = [NSData dataWithContentsOfURL:url];
NSString *result = [[NSString alloc] initWithData:responseData encoding:NSASCIIStringEncoding];

      

Until a few days ago everything worked fine, but no results from yesterday.

Could you help me? Thank.

+3


source to share


3 answers


I found my application is blocked from the site by filtering the user agent. I changed the value and now it works fine.

I changed the code like this:



NSString *userAgent = @"Mozilla/4.0 (compatible; MSIE 5.23; Mac_PowerPC)";
NSURL *url = [NSURL URLWithString: @"http://www.sanmarinocard.sm"];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:url];
[request setValue:userAgent forHTTPHeaderField:@"User-Agent"];
NSURLResponse *response = nil;
NSError *error = nil;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *result = [[NSString alloc] initWithData:responseData encoding:NSASCIIStringEncoding];

      

Thank!

+3


source


Yes, it works for me too. The server may be temporarily unavailable.

It is not recommended to use dataWithContentsOfURL: how it is synchronous and will block your application will work; if the server is not responding, it can block your application for a long time.



The preferred method would be to use NSMutableURLRequest and send an asynchronous request. This will allow your application to remain responsive while loading, and it also allows you to set a timeout interval and handle any errors more easily.

NSURL *url = [NSURL URLWithString:@"http://www.sanmarinocard.sm"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setTimeoutInterval: 10.0]; // Will timeout after 10 seconds
[NSURLConnection sendAsynchronousRequest:request
                                   queue:[NSOperationQueue currentQueue]
                       completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {

    if (data != nil && error == nil)
    {
        NSString *sourceHTML = [[NSString alloc] initWithData:data];
        // It worked, your source HTML is in sourceHTML
    }
    else
    {
        // There was an error, alert the user
    }

   }];

      

+5


source


It works fine now. The error may have occurred because the server was temporarily unavailable.

Also, as mentioned earlier, it is highly recommended to use NSUTF8StringEncoding

.

EDIT:

It can also be related to caching: dataWithContentsOfURL:

uses NSURLConnection under the hood, which caches responses by default. See this question for how to ignore it.

+1


source







All Articles