Search code examples
iosuitableviewthree20

Table view with image caching and "pull to update" option


Almost every ios app now has something like "Feed" option. Programming that usually includes fetching images from the web, caching them, handling pages, "pull to update option", etc. - all the standart stuff.

But looks like there is no standart solution for that?

  • I tried "three 20" - really big, complicated library with many modules. It really lacks good documentation! And it also had "slowdowns" while fetching images from cache.

  • Maybe I should use different small libraries for each small task separately? Like HJCache, EGO, etc.

  • Or is it better to write everything from scratch without any libraries?

Please give me advice on best practices here, i am really stuck now.


Solution

  • This one is very easy to drop in for pull to refresh.

    For image loading, I wrote the following category for UIImageView:

    // .h
    @interface UIImageView (UIImageView_Load)
    - (void)loadFrom:(NSURL *)url completion:(void (^)(UIImage *))completion;
    @end
    
    // .m
    #import "UIImageView+Load.h"
    #import <QuartzCore/QuartzCore.h>
    
    @implementation UIImageView (UIImageView_Load)
    
    - (void)loadFrom:(NSURL *)url completion:(void (^)(UIImage *))completion {
    
        NSURLRequest *request = [NSURLRequest requestWithURL:url];
        [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
            if (data) {
                self.image = [UIImage imageWithData:data];
                if (completion) completion(self.image);
            }
        }];
    }
    
    @end
    
    // To use it when building a cell
    
    //...
    
    MyModelObject *myModelObject = [self.myModel objectAtIndex:indexPath.row];
    if (myModelObject.image) {
        cell.imageView.image = myModelObject.image;
    } else {
        NSURL *url = [NSURL urlWithString:myModelObject.imageUrl];
        [cell.imageView loadFrom:url completion:^(UIImage *image) {
            // cache it in the model
            myModelObject.image = image;
            cell.imageView.image = image;
        }];
    }
    
    // ...