IOS development practices-cell download image (SDWebImage)

Source: Internet
Author: User

IOS development practices-cell download image (SDWebImage)

The first two articles are self-written image download methods. Currently, only a few lines of code can be used in a third-party framework to download images. The underlying implementation of SDWebImage is the same as previously mentioned. SDWebImage is a network image processing framework that encapsulates many methods, such as image download, image cache, download progress monitoring, and gif Processing. This greatly improves the efficiency of network image processing. It is worth using.

Github hosting address: https://github.com/rs/SDWebImage

Before downloading cell images, let's take a look at the usage of SDWebImage:

1. Import the framework and introduce the header file:

#import "UIImageView + WebCache.h"

2. How to download and cache pictures:
UIImageView + WebCache.h

// Get the URL of the current picture
-(NSURL *) sd_imageURL;

/ **
 * Download pictures asynchronously and cache
 * /
-(void) sd_setImageWithURL: (NSURL *) url;

/ **
 * Download and cache pictures asynchronously, display placeholder pictures before downloading, and replace after downloading
 * /
-(void) sd_setImageWithURL: (NSURL *) url placeholderImage: (UIImage *) placeholder;

/ **
 * Download pictures asynchronously and cache
 * @param url download image path
 * @param placeholder placeholder image, not replaced until the download is complete
 * @param options download image selection method
 * /
-(void) sd_setImageWithURL: (NSURL *) url placeholderImage: (UIImage *) placeholder options: (SDWebImageOptions) options;

/ **
 * Asynchronously download pictures and cache, you can do things in the block after completion
 * @param url download image url
 * @param completedBlock
  SDWebImageCompletionBlock: UIImage * image, NSError * error, SDImageCacheType cacheType, NSURL * imageURL)
  You can get download pictures, error information, cache type, download picture address parameters in the block, and do corresponding operations for users
 * /
-(void) sd_setImageWithURL: (NSURL *) url completed: (SDWebImageCompletionBlock) completedBlock;

/ **
 * Asynchronously download and cache pictures, provide placeholder pictures, and do things in the block after completion
 *
 * @param url T download image url
 * @param placeholder T placeholder image, not replaced until the download is complete
 * @param completedBlock
 SDWebImageCompletionBlock: UIImage * image, NSError * error, SDImageCacheType cacheType, NSURL * imageURL)
 You can get download pictures, error information, cache type, download picture address parameters in the block, and do corresponding operations for users
 * /
-(void) sd_setImageWithURL: (NSURL *) url placeholderImage: (UIImage *) placeholder completed: (SDWebImageCompletionBlock) completedBlock;

/ **
 * Asynchronously download pictures and cache, you can do things in the block after completion
 * @param url download image path
 * @param placeholder placeholder image, not replaced until the download is complete
 * @param options download image selection method
 * @param completedBlock Ibid
 * /
-(void) sd_setImageWithURL: (NSURL *) url placeholderImage: (UIImage *) placeholder options: (SDWebImageOptions) options completed: (SDWebImageCompletionBlock) completedBlock;

/ **
 * Asynchronously download pictures and cache, you can monitor the download progress, you can do things in the block after completion
 * @param url download image path
 * @param placeholder placeholder image, not replaced until the download is complete
 * @param options download image selection method
 * @param progress
 * SDWebImageDownloaderProgressBlock: NSInteger receivedSize (current download size), NSInteger expectedSize (total size)
 * @param completedBlock Ibid
 * /
-(void) sd_setImageWithURL: (NSURL *) url placeholderImage: (UIImage *) placeholder options: (SDWebImageOptions) options progress: (SDWebImageDownloaderProgressBlock) progressBlock completed: (SDWebImageCompletionBlock) completedBlock;

/ **
 * Asynchronously download pictures and cache, you can monitor the download progress, you can do things in the block after completion
 * @param url download image path
 * @param placeholder placeholder image, not replaced until the download is complete
 * @param options download image selection method
 * @param progress
 * SDWebImageDownloaderProgressBlock: NSInteger receivedSize (current download size), NSInteger expectedSize (total size)
 * @param completedBlock Ibid
 * /
-(void) sd_setImageWithPreviousCachedImageWithURL: (NSURL *) url placeholderImage: (UIImage *) placeholder options: (SDWebImageOptions) options progress: (SDWebImageDownloaderProgressBlock) progressBlock completed: (SDWebImageCompletionBlock) completedBlock;
3. all options

 // Redownload after failure
    SDWebImageRetryFailed = 1 << 0,

    // The lowest priority, when the UI interaction is in progress, some internal download operations are automatically suspended
    SDWebImageLowPriority = 1 << 1,

    // only cache memory
    SDWebImageCacheMemoryOnly = 1 << 2,

    // Progressive download, the displayed image is gradually downloaded
    SDWebImageProgressiveDownload = 1 << 3,

    // Refresh the cache
    SDWebImageRefreshCached = 1 << 4,

    // Background download
    SDWebImageContinueInBackground = 1 << 5,

    / **
     * Handles cookies stored in NSHTTPCookieStore by setting
     * NSMutableURLRequest.HTTPShouldHandleCookies = YES;
     * /
    SDWebImageHandleCookies = 1 << 6,

    // Allow invalid SSL certificate
    SDWebImageAllowInvalidSSLCertificates = 1 << 7,

    // High priority download
    SDWebImageHighPriority = 1 << 8,
    
    // Delay placeholder
    SDWebImageDelayPlaceholder = 1 << 9,

    // Change animation image
    SDWebImageTransformAnimatedImage = 1 << 10,
    
    / **
     * By default, image is added to the imageView after download. But in some cases, we want to
     * have the hand before setting the image (apply a filter or add it with cross-fade animation for instance)
     * Use this flag if you want to manually set the image in the completion when success
     * /
    SDWebImageAvoidAutoSetImage = 1 << 11

4. Memory processing: When the app receives a memory warning, we have to release the memory.
 SDWebImageManager * manager = [SDWebImageManager sharedManager];
    
    // Cancel the downloading operation
   [manager cancelAll];
    
    // Clear memory cache
    [manager.imageCache clearMemory];
    
    // Release the cache of the disk
    [manager.imageCache cleanDisk];

The above is just the method and steps for downloading images. SDWebImage also has many powerful functions, such as the introduction of SDImageCache.h in the local cache. You can see that it provides many methods in the SDImageCache file, and you can set the cache time (default one week ), Cache size, etc. Specifically, we need to take a look at the corresponding header file improvement method, which will not be elaborated here.
cell download image (SDWebImage) demo:

//
// AppsViewController.m
// cell picture download-SDWebImage
//

#import "AppsViewController.h"
#import "App.h"
#import "UIImageView + WebCache.h"

@interface AppsViewController ()
@property (nonatomic, strong) NSArray * apps;

@end

@implementation AppsViewController

-(void) viewDidLoad {
    [super viewDidLoad];
  
}

-(void) didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(NSArray *) apps {
    if (! _apps) {
        NSMutableArray * appArr = [NSMutableArray array];
        NSString * file = [[NSBundle mainBundle] pathForResource: @ "apps" ofType: @ "plist"];
        NSArray * dictArr = [NSArray arrayWithContentsOfFile: file];
        for (NSDictionary * dict in dictArr) {
            App * app = [App appWithDict: dict];
            [appArr addObject: app];
        }
        _apps = appArr;
    }
    return _apps;
}

#pragma mark-Table view data source

-(NSInteger) numberOfSectionsInTableView: (UITableView *) tableView {
    return 1;
}

-(NSInteger) tableView: (UITableView *) tableView numberOfRowsInSection: (NSInteger) section {
    return self.apps.count;
}


-(UITableViewCell *) tableView: (UITableView *) tableView cellForRowAtIndexPath: (NSIndexPath *) indexPath {
    static NSString * ID = @ "app";
    UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier: ID];
    if (! cell) {
        cell = [[UITableViewCell alloc] initWithStyle: UITableViewCellStyleSubtitle reuseIdentifier: ID];
    }
    
    App * app = self.apps [indexPath.row];
    cell.textLabel.text = app.name;
    cell.detailTextLabel.text = app.download;
    
   
    // Download pictures
    NSURL * url = [NSURL URLWithString: app.icon];
    //[cell.imageView sd_setImageWithURL: url];
    //[cell.imageView sd_setImageWithURL: url placeholderImage: [UIImage imageNamed: @ "placeholder"]];
    
    //[cell.imageView sd_setImageWithURL: url completed: ^ (UIImage * image, NSError * error, SDImageCacheType cacheType, NSURL * imageURL) {
     // NSLog (@ "% @", imageURL);
    //}];
    
    // SDWebImage download pictures
    SDWebImageOptions options = SDWebImageRetryFailed | SDWebImageLowPriority;
    [cell.imageView sd_setImageWithPreviousCachedImageWithURL: url placeholderImage: [UIImage imageNamed: @ "placeholder"] options: options progress: ^ (NSInteger receivedSize, NSInteger expectedSize) {
        NSLog (@ "Download progress:% f", (double) receivedSize / expectedSize);
    } completed: ^ (UIImage * image, NSError * error, SDImageCacheType cacheType, NSURL * imageURL) {
        NSLog (@ "Download image complete% @", image);
    }];
  
    
    return cell;
}

@end
Note: When the app receives a memory warning, it must release the memory. The entire program should implement a warning to release memory, so it is released in the applicationDidReceiveMemoryWarning method of AppDelegate.m.
-(void) applicationDidReceiveMemoryWarning: (UIApplication *) application {
    SDWebImageManager * manager = [SDWebImageManager sharedManager];
    
    // 1. Cancel the downloading operation
   [manager cancelAll];
    
    // 2. Clear memory cache
    [manager.imageCache clearMemory];
}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.