如何通过URL获取图片
异步获取图片,通过队列实现,而且图片会有缓存,在下次请求相同的链接时,系统会自动调用缓存,而不从网上请求数据。
[objc] view plaincopy
UIImageView *p_w_picpathView = [[UIImageView alloc] initWithFrame:CGRectMake(0.0f, 100.0f, 100.0f, 100.0f)]; [p_w_picpathView setImageWithURL:[NSURL URLWithString:@"http://i.imgur.com/r4uwx.jpg"]placeholderImage:[UIImage p_w_picpathNamed:@"placeholder-avatar"]]; [self.view addSubview:p_w_picpathView];
上面的方法是官方提供的,还有一种方法,
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.scott-sherwood.com/wp-content/uploads/2013/01/scene.png"]];
AFImageRequestOperation *operation = [AFImageRequestOperation p_w_picpathRequestOperationWithRequest:request p_w_picpathProcessingBlock:nil success:^(NSURLRequest *request, NSHTTPURLResponse*response, UIImage *p_w_picpath) {
self.backgroundImageView.p_w_picpath = p_w_picpath;
} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error) {
NSLog(@"Error %@",error);
}];
[operation start];
如果使用第一种URLWithString: placeholderImage:会有更多的细节处理,其实实现还是通过AFImageRequestOperation处理,可以点击URLWithString: placeholderImage:方法进去看一下就一目了然了。所以我觉得还是用第一种好。