IOS via button Click asynchronously Load Picture _ios

Source: Internet
Author: User
Tags uikit

Compare the original method:

Copy Code code as follows:

AsyncImageView.h:
#import <UIKit/UIKit.h>
@interface Asyncimageview:uiview
{
nsurlconnection* connection;
nsmutabledata* data;
}
-(void) Loadimagefromurl: (nsurl*) URL;
@end
ASYNCIMAGEVIEW.M:
#import "AsyncImageView.h"
@implementation Asyncimageview
-(ID) initWithFrame: (CGRect) frame
{
self = [super Initwithframe:frame];
if (self) {
Initialization code
}
returnself;
}
-(void) Loadimagefromurl: (nsurl*) URL {
if (connection!=nil) {[Connection release];}
if (data!=nil) {[Data release];}
nsurlrequest* request = [Nsurlrequest Requestwithurl:url
Cachepolicy:nsurlrequestuseprotocolcachepolicy
timeoutinterval:60.0];
connection = [[Nsurlconnection alloc]
Initwithrequest:request Delegate:self];
}
-(void) connection: (Nsurlconnection *) theconnection
Didreceivedata: (NSData *) Incrementaldata {
if (Data==nil) {
data =
[[Nsmutabledata alloc] initwithcapacity:2048];
}
[Data Appenddata:incrementaldata];
}
-(void) connectiondidfinishloading: (nsurlconnection*) theconnection {
[Connection release];
Connection=nil;
if ([[Self subviews] count] > 0) {
[[[Self subviews] objectatindex:0] removefromsuperview];
}
Uiimageview *imageview = [[[[Uiimageview alloc] initwithimage:[uiimage Imagewithdata:data]] autorelease];
Imageview.contentmode = Uiviewcontentmodescaleaspectfit;
Imageview.autoresizingmask = (Uiviewautoresizingflexiblewidth | Uiviewautoresizingflexibleheight);
[Self addsubview:imageview];
Imageview.frame = Self.bounds;
[ImageView Setneedslayout];
[Self setneedslayout];
[Data release];
Data=nil;
}
-(uiimage*) Image {
uiimageview* IV = [[self subviews] objectatindex:0];
Return[iv image];
}
-(void) Dealloc {
[Connection Cancel];
[Connection release];
[Data release];
[Super Dealloc];
}
@end

Method Two:

Copy Code code as follows:

@interface UIButton (Asyncimage)
Size by point
-(void) Setimagefromurl: (NSString *) urlstring adjusttosize: (cgsize) Size completion: (void (^) (void) Completion Logo: ( UIImage *) Logoimage;
@end
@implementation UIButton (Asyncimage)
-(void) Setimagefromurl: (NSString *) urlstring adjusttosize: (cgsize) Size completion: (void (^) (void) Completion Logo: ( UIImage *) Logoimage
{
Dispatch_async (Dispatch_get_global_queue (dispatch_queue_priority_default, 0), ^{
UIImage *image = nil;
Nsurl *url = [Nsurl urlwithstring:urlstring];
NSData *data = [NSData Datawithcontentsofurl:url];
Image = [UIImage imagewithdata:data];
if (image) {
if (! Cgsizeequaltosize (size, Cgsizezero)) {
Image = [UIImage imagewithcgimage:image. Cgimage scale:[self scaleimage:image adjusttosize:size] orientation:image.imageOrientation];
}
if (logoimage) {
Image = [self addlogoimage:logoimage toimage:image];
}
Dispatch_async (Dispatch_get_main_queue (), ^{
[Self setimage:image forstate:uicontrolstatenormal];
Completion ();
});
}
else {
NSLog (@ "Async load error.");
}
});
}
Scale pictures to fit button size
-(CGFloat) Scaleimage: (UIImage *) image adjusttosize: (cgsize) size
{
CGFloat XScale = size.width/image.size.width;
CGFloat Yscale = size.height/image.size.height;
Return 1.0/min (XScale, Yscale);
}
-(UIImage *) Addlogoimage: (UIImage *) logo toimage: (uiimage *) img
{
Get image width and height
CGFloat scale = [UIScreen mainscreen].scale;
int w = scale * img.size.width;
int h = scale * img.size.height;
int logowidth = Logo.scale * logo.size.width;
int logoheight = Logo.scale * logo.size.height;
Cgcolorspaceref colorspace = Cgcolorspacecreatedevicergb ();
Create a graphic context with cgbitmapcontextcreate
Cgcontextref context = Cgbitmapcontextcreate (NULL, W, H, 8, 4 * W, colorspace, Kcgimagealphapremultipliedfirst);
Cgcontextdrawimage (context, CGRectMake (0, 0, W, h), IMG. Cgimage);
Cgcontextdrawimage (Context, CGRectMake (w-logowidth, 0, Logowidth, logoheight), [logo cgimage]);
Cgimageref imagemasked = cgbitmapcontextcreateimage (context);
Cgcontextrelease (context);
Cgcolorspacerelease (ColorSpace);
return [UIImage imagewithcgimage:imagemasked Scale:scale orientation:img.imageOrientation];
}
@end

Method Three:

#import <Foundation/Foundation.h>
#import "StringUtils.h"

@interface imagemanager:nsobject
{
  nsmutabledictionary *_imagedict;
  Nsmutablearray *_imagearr;
}

@property (nonatomic, strong) NSString *httpurl;
@property (nonatomic, strong) nsmutabledictionary *imagedict;

@property (nonatomic, assign) dispatch_queue_t Networkqueue;

+ (Imagemanager *) sharedinstance;


-(void) Asyncimage: (NSString *) imagename ImageView: (Uiimageview *) ImageView;
Queue
-(void) Asyncimageinsert: (NSString *) imagename ImageView: (Uiimageview *) ImageView Insert: (BOOL) insert;
Do not download data before downloading
-(void) Asyncimagecleanold: (NSString *) imagename ImageView: (Uiimageview *) ImageView Cleanold: ( BOOL) Cleanold;

@end

Implementation file:

IMAGEMANAGER.M//Myb-ios////Created by Warrior Gao on 13-6-5. Copyright (c) 2013 51myb.
All rights reserved. #import "ImageManager.h" @interface Imagemanager () @end The maximum number of @implementation Imagemanager//cache of a picture, static int Counte

R = 0;

@synthesize imagedict = _imagedict;
  Singleton + (Imagemanager *) sharedinstance {static ID instance;
  Static dispatch_once_t Oncetoken;
  Dispatch_once (&oncetoken, ^{instance = self.new;
  });
return instance;  }-(ID) init {if ((self = [super init]) {self.networkqueue = Dispatch_queue_create ("Com.warrior.network.image"),
    NIL);
    _imagedict = [[Nsmutabledictionary alloc] init];
  _imagearr = [[Nsmutablearray alloc] init];
return self; }-(NSString *) Filefullpath: (NSString *) fileName {nsstring *cachepath = [Nssearchpathfordirectoriesindomains (NSCache
  
  Sdirectory, Nsuserdomainmask, YES) objectatindex:0];
  
  NSString *filefullpath = [NSString stringwithformat:@ "%@/%@", Cachepath,filename]; RetUrn Filefullpath; //Do not before downloading data-(void) Asyncimagecleanold: (NSString *) imagename ImageView: (Uiimageview *) ImageView cleanold: (BOOL)
  Cleanold {if (cleanold) {[_imagearr removeallobjects];
[Self asyncimage:imagename imageview:imageview]; }//Queue up, priority-(void) Asyncimageinsert: (NSString *) imagename ImageView: (Uiimageview *) ImageView Insert: (BOOL) Insert {if (S
  Tringutils Isempty:imagename]) {return; } nsdata *data = [NSData datawithcontentsoffile:[self filefullpath:[imagename stringbyreplacingoccurrencesofstring:@ "
  /"withstring:@"-"]"];
    if (data = = nil) {[_imagedict setvalue:imageview forkey:imagename];
    if (insert) {[_imagearr insertobject:imagename atindex:0];
    else {[_imagearr addobject:imagename];
  } [self cacheimage];
  else {[ImageView setimage:[uiimage imagewithdata:data]]; }//Normal, Append to back-(void) Asyncimage: (NSString *) imagename ImageView: (Uiimageview *) ImageView {[Self Asyncimageinsert:ima GeName Imageview:imageview Insert:no]; ///Async cache picture to local, up to two threads-(void) Cacheimage {for (; counter < 2 && _imagearr.count > 0; counter++) {N
    Sstring *imagename = nil;
      @synchronized (self) {imagename = [[_imagearr objectatindex:0] copy];
    [_imagearr removeobjectatindex:0];
    
    } if (imagename = = nil) continue;
      Dispatch_async (Self.networkqueue, ^{NSLog (@ "Starting:%@", imagename);
      UIImage *avatarimage = nil;
      Nsurl *url = [Nsurl urlwithstring:[nsstring stringwithformat:@ "%@%@", Self.httpurl, ImageName]];
      NSData *responsedata = [NSData Datawithcontentsofurl:url]; if (Responsedata.length > 0) {[ResponseData writetofile:[self filefullpath:[imagename Stringbyreplacingoc
        currencesofstring:@ "/" withstring:@ "-"]] atomically:no];
        Avatarimage = [UIImage imagewithdata:responsedata];
        
        NSLog (@ "Finishing:%@", imagename); if (avatarimage) {Dispatch_async (dispAtch_get_main_queue (), ^{uiimageview *imageview = [_imagedict objectforkey:imagename];
            if (ImageView!= nil && avatarimage!= nil) {[ImageView setimage:avatarimage];
            } [_imagedict Removeobjectforkey:imagename];
          [ImageName release];
        });
      }} counter--;
    [Self cacheimage];
    
  }); }} @end

The above is the entire contents of this article, I hope you can enjoy.

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.