Ploetzeneder
Ploetzeneder

Reputation: 1321

How to set timeout for dataWithContentsOfURL:url

I would like to download with a shorter timeout, so that it is faster, and to prevent the app from crashing on a bad connection.

- (void) CreateTitleView {
    NSURL* url;
    NSData* imageData;
    imageData = [NSData dataWithContentsOfURL:url ];
    UIImage* image = [UIImage imageWithData:imageData];
}

I am not good in objective C, so I ask for your help, to do this. Thanks.

Upvotes: 5

Views: 7070

Answers (2)

DrMickeyLauer
DrMickeyLauer

Reputation: 4674

These days, it's possible. The API is like that:

NSURLResponse* urlResponse;
NSError* error;
NSMutableURLRequest* urlRequest = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:20];
NSData* d = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:&urlResponse error:&error];

Upvotes: 13

Perception
Perception

Reputation: 80603

You cannot control the download speed by setting a timeout. That would only control how long your application waited before giving up on the download. You should refactor your application to load the image data in the background, so that the UI remains responsive till the download is complete.

Check out NSURLConnection (sendAsynchronousRequest), or AFNetworking.

Upvotes: 2

Related Questions