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?
问题:
回答1:
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
回答2:
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.
回答3:
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.
回答4:
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];
回答5:
if what you need is just downloading image from a url, don't bother to use any libraries, just a simple dispatch_async call should be OK. like this:
dispatch_async( dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0 ), ^(void)
{
NSData * data = [NSData dataWithContentsOfURL:imageUrl];
dispatch_async( dispatch_get_main_queue(), ^(void){
self.image = [UIImage imageWithData:data];
});
});