Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSData dataWithContentsOfURL cache

NSData +dataWithContentsOfURL has any kind of caching by default? Has anyone experimented some kind of problems using this method, what is the most efficient way to get Data from the web?

like image 392
cesarnicola Avatar asked Aug 23 '10 15:08

cesarnicola


4 Answers

Use ASIHTTPRequest. It's a third party HTTP client library that makes network interaction MUCH simpler, and has very nice caching functions.

UPDATE: Just got a downvote on this answer, which is a good reminder to come back and update. Lot has changed since August '10. Most notably: ASIHTTPRequest is now deprecated, and its author is encouraging people to use something else. AFNetworking seems a popular choice.

like image 61
Dan Ray Avatar answered Nov 16 '22 04:11

Dan Ray


It seems that on iPhone5s the default policy is to cache (unlinke iPhone5 and earlier).

You can handle via the options parameter the cache policy for NSData . For example,if you want to avoid cache, the following snipped can be used :

[[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:url] options:NSDataReadingUncached error:nil];
like image 44
MichaelCMS Avatar answered Nov 16 '22 03:11

MichaelCMS


It's best to use NSURLConnection. The NSURLRequest you give it can be configured to do the caching the way you want but by default it will just do standard caching of HTTP resources that have the appropriate headers in their response.

This is what I do:

NSData *data = [NSURLConnection sendSynchronousRequest:
                [NSURLRequest requestWithURL:url]
                                     returningResponse:nil
                                                 error:&error];

Make sure to put this in an NSOperationQueue that isn't your main queue or off-load it from the main thread in some other way, though. Alternatively, use an asynchronous request.

like image 22
lhunath Avatar answered Nov 16 '22 03:11

lhunath


The documentation doesn't say that it will cache, so I think we should assume that they don't do any caching.

Which kinds of data you want to get

UIImage : yes, I think you should use NSData

Video: you should use MPMoviePlayerController for streaming

Text: I think you can do normal NSUrlConnection. It also has asynchronous, synchrnous and caching

like image 27
vodkhang Avatar answered Nov 16 '22 03:11

vodkhang