Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 625
Ploetzeneder Avatar asked Apr 17 '12 19:04

Ploetzeneder


2 Answers

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];
like image 126
DrMickeyLauer Avatar answered Sep 23 '22 00:09

DrMickeyLauer


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.

like image 38
Perception Avatar answered Sep 25 '22 00:09

Perception