SDWebImage-master 是一个非常强大的三方。
当需要应用SDWeb时把文件夹里的SDWebImage文件夹放入工程里。
在需要使用网络获取图片的文件里进入头文件#import "UIImageView+WebCache.h"即可使用相应的api。
首先最基本的方法展示(仅获取图片)
1 #import "ViewController.h" 2 #import "UIImageView+WebCache.h" 3 4 @interface ViewController () 5 6 @end 7 8 @implementation ViewController 9 10 - (void)viewDidLoad { 11 [super viewDidLoad]; 12 13 NSString * urlString = [NSString stringWithFormat:@"http://localhost/tupian.jpg"]; 14 15 NSURL * url = [NSURL URLWithString:urlString]; 16 17 UIImageView * imageView = [[UIImageView alloc]init]; 18 19 imageView.frame = CGRectMake(0, 20, CGRectGetWidth(self.view.frame), 300); 20 21 [imageView sd_setImageWithURL:url]; 22 23 [self.view addSubview:imageView]; 24 25 } 26 27 28 @end
*温馨提示:SDWebImage-master可以在github上下载。*
防止网速差刷不出来图片,会出现留白现象,为此加了占位图片;图片不唯一可以自己配置;
1 #import "ViewController.h" 2 #import "UIImageView+WebCache.h" 3 4 @interface ViewController () 5 6 @end 7 8 @implementation ViewController 9 10 - (void)viewDidLoad { 11 [super viewDidLoad]; 12 13 NSString * urlString = [NSString stringWithFormat:@"http://localhost/tupian.jpg"]; 14 15 NSURL * url = [NSURL URLWithString:urlString]; 16 17 UIImageView * imageView = [[UIImageView alloc]init]; 18 19 imageView.frame = CGRectMake(0, 20, CGRectGetWidth(self.view.frame), 300); 20 21 [imageView sd_setImageWithURL:url placeholderImage:[UIImage imageNamed:@"图片名称"]]; 22 23 [self.view addSubview:imageView]; 24 25 } 26 27 28 @end
1 // 2 // ViewController.m 3 // CX-SDWebImage-master 4 // 5 6 #import "ViewController.h" 7 #import "UIImageView+WebCache.h" 8 9 @interface ViewController () 10 11 @end 12 13 @implementation ViewController 14 15 - (void)viewDidLoad { 16 [super viewDidLoad]; 17 18 NSString * urlString = [NSString stringWithFormat:@"http://localhost/tupian.jpg"]; 19 20 NSURL * url = [NSURL URLWithString:urlString]; 21 22 UIImageView * imageView = [[UIImageView alloc]init]; 23 24 imageView.frame = CGRectMake(0, 20, CGRectGetWidth(self.view.frame), 300); 25 26 [imageView sd_setImageWithURL:url completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) { 27 28 NSLog(@"%@",image); 29 //枚举 30 NSLog(@"%ld",(long)cacheType); 31 32 NSLog(@"%@",imageURL); 33 34 }]; 35 36 [self.view addSubview:imageView]; 37 38 } 39 /* 40 结果 41 2016-03-18 13:12:18.091 CX-SDWebImage-master[4626:283982] <UIImage: 0x7fe8a3f0d900>, {250, 250} 42 2016-03-18 13:12:18.092 CX-SDWebImage-master[4626:283982] 1 43 2016-03-18 13:12:18.092 CX-SDWebImage-master[4626:283982] http://localhost/tupian.jpg 44 */ 45 46 47 @end