NSURLSession for loading network images + cache

There are many third party libraries for loading network images and then storing them to disk and / or memory.

However, it is very easy to implement it using a simple NSURLSession API call.

here is the code:

     NSURLCache *myCache = [[NSURLCache alloc] initWithMemoryCapacity: 16384 diskCapacity: 268435456 diskPath: cachePath]; // these numbers are only for the usage example.
     defaultConfigObject.URLCache = myCache;
     defaultConfigObject.requestCachePolicy = NSURLRequestUseProtocolCachePolicy;
     _session = [NSURLSession sessionWithConfiguration: defaultConfigObject delegate:self delegateQueue: [NSOperationQueue mainQueue]];

     _dataTask = [_session dataTaskWithURL:url completionHandler:^(NSData *data, NSURLResponse *response, NSError *error){

        if (!error){
            UIImage* theImage = [UIImage imageWithData:data];
            dispatch_async(dispatch_get_main_queue(), ^{
                self.image = theImage;

            });
        }
    }];
    [_dataTask resume];

      

This code downloads the image (from the given url) and stores it on the memory + disk according to the http caching policy.

Getting MyNetworkImageView from a UIImageView and adding the above code to the setURL: method is also straight forward.

My question is :

What are the benefits of using third-party frameworks like AFNetworking, FastImageCache, SDWebImage, SDImageCache?

+3


source to share


2 answers


  • Caching in this framework is more deterministic. NSURLCache

    used NSURLSession

    is (a) somewhat opaque (for example, I've never seen a 5% threshold documented); and (b) controlled by the response headers provided by your server.

  • Before just declaring NSURLCache

    "good enough", I would suggest rigorously test the application and make sure the caching (esp persistent cache cache: launching the application, loading images; terminating (not just pausing) the application, restart the application) works as you hope ... Be sure to check for both runtime caching and persistent storage caching.

  • As an aside, your memory cache appears to be very small (and anything over 5% of the cache size will not be cached). This is a matter of opinion, but I usually expected to see something closer to 16mb rather than 16kb. However, this will not cache anything over 800 bytes!)

  • This framework also offers many other benefits.

    • The categories UIImageView

      provided by AFNetworking and SDWebImage are the easiest way to get an asynchronous image. Specifically, when cells are reused in a table / collection view, it will override previous requests, making sure that image requests for visible cells are prioritized. (You don't want to quickly scroll to the 100th row in the table and wait for up to 99 images that don't have long visibility to load before you start loading images for visible cells.)

    • When generating complex HTTP requests, AFNetworking allows you to focus on the application logic rather than writing and testing complex network code.



The bottom line, based on NSURLCache in iOS, has been problematic in the past, especially if you're not in control of the server. These classes also offer other benefits (for example with UIImageView categories).

+1


source


NSURLCache is a great tool, especially if you need re-attestation mechanisms and NSURLCache handles HTTP transparency transparently for you. NSURLSession is also a good step forward for Cocoa networks.

However, it is not easy to efficiently extract images. There are some special requirements you may have for your application:

  • Avoid decompressing the image in the main stream, which is expensive, especially for jpg.
  • Have a separate in-memory cache layer on top of NSURLCache to store decompressed images and be able to fetch them synchronously on the main thread. Managing your in-memory cache is not that easy, even if you are using NSCache.
  • You have an abstraction on top at the network level to be able to add support for more image formats when needed, like gif

    or webp

    . And expand your image selection in other ways.
  • Group the same image requests and not create excessive session tasks.
  • Be able to swing images effectively
  • Try to get a low-res placeholder first and then wait for a high-res image.

And further.



AFNetworking, FastImageCache, SDWebImage, SDImageCache

None of these frameworks use NSURLSession (some even have their own disk cache implementations), please have a look at Nuke / DFImageManager . It is built on top of NSURLSession, has all the features listed above, and also has several routines that combine things like AFNetworking * as a networking stack, FLAnimatedImage as an animated GIF engine, and more.

* AFNetworking is based on NSRULSession, but their implementation of fetching images is still based on top of NSURLConnection (AFHTTPRequestOperation).

0


source







All Articles