IOS asynchronous Download Picture Instance code _ios

Source: Internet
Author: User

It's written in front.

In iOS development, whether in UITableView or Uicollectionview, it is a more common requirement to get pictures from the network and set them to the cell. Although there are a lot of existing third-party libraries can be downloaded and cached features are packaged for developers to use, but from the learning point of view, understand the source code, understanding the principle of the combination of their actual needs to write their own code is very necessary. In the just end of the demo, useful to asynchronous picture download function, this note is a simple collation of the entire implementation.

Basic ideas

Add a uiimageview to the cell

cell has the URL, initiates the download request, registers the next completion notice, obtains the download picture in the notification processing time and sets

• Download Management class is responsible for opening the download thread and a variety of cache (memory + files), download completed after the download to complete the notification

• To avoid the image dislocation caused by cell reuse and asynchronous downloading, the cell sets the default picture for itself ImageView before launching the download, and sets the tag for ImageView

Overall framework

Critical code

Cell initialization, and sign up for download completion notices

@interface Sqphotocell ()
@property (Strong, nonatomic) Uiimageview *photoview;
The tag points to the URL of the currently visible picture, filtering out the URL of the picture that has slipped out of the screen
@property (strong, nonatomic) NSString *imageviewtag;
@end
-(ID) initWithFrame: (CGRect) frame
{
self = [super Initwithframe:frame];
if (self)
{
_photoview = [[Uiimageview alloc] initwithframe:cgrectzero];
_photoview.userinteractionenabled = YES;
[Self.contentview Addsubview:_photoview];
_imageviewtag = @ "";
Register download complete notification
[[nsnotificationcenter defaultcenter] addobserver:self
selector: @selector (downloadcallback :)
name:notification_download_callback
object:nil];
}
return self;
}

Cell Notification handling Events

Notification handling event
-(void) Downloadcallback: (nsnotification *) Noti
{
nsdictionary *notidic = noti.userinfo;
NSString *urlstr = [notidic objectforkey:@ "Urlstr"];
UIImage *image = [Notidic objectforkey:@ "image"];
if ([Self.imageviewtag isequaltostring:urlstr])
{
self.photoView.image = image;
}
}

Cell initiates download request

-(void) Setimagewithurl: (NSString *) urlstr placeholder: (uiimage *) placeholder
{
Self.imageviewtag = urlStr ;
A preset picture used to clear a picture that might have existed before
self.photoView.image = placeholder;
if (urlstr)
{
Sqwebimagemanager *manager = [Sqwebimagemanager Sharedmanager];
[Manager Downloadimagewithurlstring:urlstr];
}
[Self setneedsdisplay];
}

Download Admin class download function

-(void) downloadimagewithurlstring: (NSString *) urlstr {//1. To determine the memory cache {Urlstr:image} uiimage *cacheimage = [Self.imagecach
e Objectforkey:urlstr];
if (cacheimage!= nil) {//Send notification of download completion and return urlstr and picture [self postdownloadcompletenotification:urlstr withimage:cacheimage];
Return
}//2. To judge the sandbox cache nsstring *cacheimagepath = [self cacheimagepathwithurlstring:urlstr];
Cacheimage = [UIImage Imagewithcontentsoffile:cacheimagepath]; if (cacheimage!= nil) {//From the sandbox read to the picture, set to the memory cache, convenient next time can be read directly from memory [Self.imagecache setobject:cacheimage FORKEY:URLSTR];
Back to picture [self postdownloadcompletenotification:urlstr withimage:cacheimage];
Return 
}//3. To determine the operation cache, to prevent the picture multiple downloads {urlstr:operation} if (Self.operationcache[urlstr]!= nil) {//There is an operation downloading this picture NSLog (@ "There is operation downloading this picture");
Return //1. Define download picture operation sqdownloadoperation *downloadoperation = [Sqdownloadoperation downloadoperationwithurlstring:urlstr
Cacheimagepath:cacheimagepath]; Sets the callback that completes the download of the operation, and the callback is __weak typeof (Downloadoperation) when the Downloadoperation Main method completes execution WeakdownloaDoperation = downloadoperation;  Downloadoperation.completionblock = ^ () {//1. Get the downloaded finished image uiimage *image = [weakdownloadoperation getdownloadimage];//2.
Removing operations from the action buffer pool [Self.operationcache removeobjectforkey:urlstr]; 3. Determine if the image is empty (thumbnail) if (images!= nil) {//Set the downloaded picture to the picture memory cache [Self.imagecache setobject:image forkey:urlstr];//4. Main thread callback [[Nsoper Ationqueue Mainqueue] addoperationwithblock:^{//Issuing download completion notice [self postdownloadcompletenotification:urlstr withImage:
Image];
}]; else {//If the picture is empty, return the default picture image when the download fails = [UIImage imagenamed:@ "default.jpg"];//4. Main thread callback [[Nsoperationqueue Mainqueue] AddO
perationwithblock:^{//Issuing download completion notices [self postdownloadcompletenotification:urlstr withimage:image];
}
};
2. Add the download picture operation to the queue [Self.downloadqueue addoperation:downloadoperation];
3. Add the download picture operation to the download operation cache [Self.operationcache setobject:downloadoperation forkey:urlstr]; }-(void) Postdownloadcompletenotification: (NSString *) urlstr withimage: (UIImage *) image {nsdictionary = [ Nsdictionary DictionarywithobjeCtsandkeys:urlstr, @ "Urlstr", image, @ "image", nil]; [[Nsnotificationcenter defaultcenter]postnotificationname:notification_download_callback Object:nil UserInfo:dic]
; }

Used in the controller

-(Uicollectionviewcell *) CollectionView: (Uicollectionview *) CollectionView Cellforitematindexpath: (NSIndexPath *) Indexpath
{
Sqphotocell *cell = (Sqphotocell *) [CollectionView dequeuereusablecellwithreuseidentifier: Reuseidentifier
Forindexpath:indexpath];
UIImage *placeholder = [uiimage imagenamed:@ "gray.jpg"];
NSString *imageurl = @ "Http://www.taopic.com/uploads/allimg/110925/9117-11092509545328.jpg";
[Cell Setimagewithurl:imageurl Placeholder:placeholder];
return cell;
}

It's written in the back.

This asynchronous download picture of the idea is modeled after Sdwebimage, although you can see the source code, there are some articles and blog to explain the idea, but their own without contact with multithreaded programming in the case of learning this download ideas or spend a lot of time. The early days have been a little anxious, want to hurry to make, in a lot of things are ignorant of the situation to do, and then slowly realized that, in fact, slow is fast, slow down, the problem to think clearly before the implementation although the early feeling is not good, but to the back of the more can find this slow benefits.

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.