代码介绍:首先开启一个线程请求网络图片,图片下载成功之后保存到相册中。代码简单易懂。
@implementation ViewController
{
NSData *data;
}
- (void)viewDidLoad {
[super viewDidLoad];
UIImageView *imageview=[[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 300, 200)];
[imageview setBackgroundColor:[UIColor grayColor]];
[self.view addSubview:imageview];
dispatch_async(dispatch_get_global_queue(0, 0), ^{
data=[NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://image.baidu.com/search/down?tn=download&word=download&ie=utf8&fr=detail&url=http%3A%2F%2Fpic26.nipic.com%2F20121223%2F9252150_195341264315_2.jpg&thumburl=http%3A%2F%2Fimg3.imgtn.bdimg.com%2Fit%2Fu%3D806135425%2C801140138%26fm%3D21%26gp%3D0.jpg"]];
dispatch_async(dispatch_get_main_queue(), ^{
[imageview setImage:[UIImage imageWithData:data]];
UIImageWriteToSavedPhotosAlbum(imageview.image, self, @selector(imageSavedToPhotosAlbum:didFinishSavingWithError:contextInfo:), nil);
NSLog(@"下载完成1");
});
NSLog(@"下载完成2");
});
NSLog(@"下载完成3");
}
- (void)imageSavedToPhotosAlbum:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
{
NSString *message = @"呵呵";
if (!error) {
message = @"成功保存到相册";
}else
{
message = [error description];
}
NSLog(@"message is %@",message);
}