iOS multithreaded -05-multi-image download

Source: Internet
Author: User

Frequently asked questions and how to solve
    • Image repeat Download
      • Save the memory in memory or in a sandbox.
    • If you download a large number of images, there will be a UI interface is not smooth phenomenon
      • Perform the download operation on the child thread, and then go back to the main thread to refresh the UI interface.
    • Image display disorder caused by cell recycling
      • Specifies that the Indexpath row of the table is refreshed.
    • Subtitle type of cell, cannot display picture
      • Subtitle in a cell of type ImageView only set the picture the first time the cell is returned, otherwise the picture will not display (refresh the table too). You can work around this problem by setting up a placeholder picture.
Mind Mapping

Specific implementation
  • Its core code is mainly in the return of TableView to create the proxy method of the cell, so the following main implementation of the method to parse

  • Main process

      • Sets the model class, which contains the following properties
    /**图片*/@property (nonatomic, strong) NSString *icon;/**名字*/@property (nonatomic, strong) NSString *name;/**下载量*/@property (nonatomic, strong) NSString *download;
      • The member properties that need to be used
    /**模型数组,用来存放每个cell的数据模型*/@property (nonatomic, strong) NSArray *apps;/**操作队列,操作只有添加到队列才有可能并发执行*/@property (nonatomic, strong) NSOperationQueue *queue;/**用于在内存中缓存图片,部分避免图片被多次下载*/@property (nonatomic, strong) NSMutableDictionary *imageCache;/**标记当前所有正在执行的操作,避免正在执行的操作被重复执行*/@property (nonatomic, strong) NSMutableDictionary *operations;
    • Core code of the method that created the cell

        • Take a picture from the memory cache
      //内存中缓存的图片在imagCache数组中self.imageCache[app.icon]
        • Take a picture from the sandbox
      //Get file pathNSString*cachepath = [Nssearchpathfordirectoriesindomains (Nscachesdirectory, Nsuserdomainmask,YES) Firstobject];//Get file nameNSString*filename = [App. IconLastpathcomponent];//Calculate the full pathNSString*file = [CachePath stringbyappendingpathcomponent:filename];//Load the data in the sandboxNSData *data = [NSData datawithcontentsoffile:file];//To determine if data is available, otherwise download data from the networkif(data) {//sandbox with data    UIImage*image = [UIImageImagewithdata:data]; Cell. ImageView. Image= Image;//Save in Dictionary (memory)     Self. Imagecache[App. Icon] = Cell. ImageView. Image;}
        • Download data from the network
      //If a cell of type subtitle is to display a picture, the picture (or placeholder picture) must be displayed when the cell is first put backCell. ImageView. Image= [UIImageimagenamed:@"1"];//Get operations in the operations queueNsoperation *operation = Self. Operations[App. Icon];if(Operation = =Nil){//There is no download operation for this picture    //Create a download picture operationOperation = [Nsblockoperation blockoperationwithblock:^{//Load data via URLNSData *data = [NSData datawithcontentsofurl:[NsurlUrlwithstring:app. Icon]];//Data Load Failure        if(Data = =Nil)        {//Remove operation so that data can be requested again when the table is refreshed[ Self. OperationsRemoveobjectforkey:app. Icon];return; }//nsdata conversion to UIImage        UIImage*image = [UIImageImagewithdata:data];//store in a dictionary         Self. Imagecache[App. Icon] = image;//thread sleep, analog big data download[NsthreadSleepfortimeinterval:1];//Back to main thread display picture[[Nsoperationqueue Mainqueue] addoperationwithblock:^{//Refresh the table via Indexpath, where there are already pictures in the memory cache[ Self. TableViewReloadrowsatindexpaths:@[indexpath] Withrowanimation:uitableviewrowanimationnone]; }];//write picture to sandbox[Data writetofile:file atomically:YES];//Remove operation to ensure that images that are not downloaded can be re-downloaded when the table is refreshed[ Self. OperationsRemoveobjectforkey:app. Icon]; }];//Add an action to a queue[ Self. QueueAddoperation:operation];//Ensure that images are not downloaded repeatedly     Self. Operations[App. Icon] = operation;
Through a third-party framework (Sdwebimage)
    • Sdwebimage can greatly simplify the multi-image download task
    • By extending the classification of the Uiimageview, the multi-image download function is implemented in the classification method, exposing only a simple network interface to the external user.
    • Include category header file Uiimageview+webcache.h

    • The implementation of image download function

      • Method One
      - (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder/**     url:图片的地址     placeholder:占位图片*/
      • Method Two
      - (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageCompletionBlock)completedBlock/**     progressBlock:下载过程中的回调Block,可以在该Block中计算下载进度     completedBlock:下载完毕的回调方法*/

The latest status of this blog will be synced to Sina Weibo account: secular island

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

iOS multithreaded -05-multi-image download

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.