iOS开发之SDWebImage的使用

SDWebImage是iOS开发中一个常用的第三方库,主要用于图片的显示和缓存,可以用很简单的代码实现网络图片的显示并缓存到本地,下面记录的是SDWebImage的用法:

1、xcode新建项目TestSDWebImage,并使用cocoapods引入SDWebImage库,如果还不清楚cocoapods的使用,可以参考这篇博文

这里给出Podfile文件的内容:

platform:ios, ‘7.0’
pod 'SDWebImage', '~> 3.7.5'
2、引入SDWebImage的头文件:

#import "UIImageView+WebCache.h"
3、使用WebImage加载网络图片

这里我们在Main.storyborad中拖入一个UIImageView控件,然后在ViewController.m文件中加入下面的代码:

#import "ViewController.h"
#import "UIImageView+WebCache.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    [self showImage];
}

- (void)showImage {
    NSString *urlStr = @"http://g.hiphotos.baidu.com/image/pic/item/6c224f4a20a446230761b9b79c22720e0df3d7bf.jpg";
    NSURL *url = [NSURL URLWithString:urlStr];
    // 用法一  在UIImageView上显示URL地址中的图片
//    [self.imageView sd_setImageWithURL:url];
    
    // 用法二  completed是加载完成后的回调block
//    [self.imageView sd_setImageWithURL:url completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
//        NSLog(@"load picture complete!");
//    }];
    
    // 用法三  placeholder是加载完成前显示的默认图片
    [self.imageView sd_setImageWithURL:url placeholderImage:[UIImage imageNamed:@"loading.jpg"] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
        NSLog(@"load complete!");
    }];
}

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

@end
可以看到上面的showImage方法就是加载图片的代码,仅仅用一个sd_setImageWithURL方法就完成了网络图片的加载,在运行上面的代码的时候,可能会报错,这里也需要在info.plist文件中允许http请求,如果不清楚info.plist文件怎么配置,可以参考 这篇博文。

执行成功后模拟器中显示如下图所示:





你可能感兴趣的:(ios开发,SDWebImage)