NSData dataWithContentsOfURL cache

2019-03-19 18:11发布

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?

5条回答
一夜七次
2楼-- · 2019-03-19 18:13

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];
查看更多
\"骚年 ilove
3楼-- · 2019-03-19 18:14

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

查看更多
啃猪蹄的小仙女
4楼-- · 2019-03-19 18:15

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.

查看更多
SAY GOODBYE
5楼-- · 2019-03-19 18:20

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];
    });
});
查看更多
淡お忘
6楼-- · 2019-03-19 18:36

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.

查看更多
登录 后发表回答