图片下载保存显示

来源:互联网 发布:盘锦数控编程人才网 编辑:程序博客网 时间:2024/05/19 13:18

将图片下载好保存到沙盒,然后主线程中刷新UI

- (IBAction)downLoadClick:(UIButton *)sender{    //dataWithContentsOfURL  是一个同步执行的方法,如果写在主线程中,网速慢的情况下会导致主线程阻塞    //detachNewThreadSelector  需要开启一个分线程调用下载方法    [NSThread detachNewThreadSelector:@selector(downLoadImage) toTarget:self withObject:nil];}- (void)downLoadImage{    NSURL *url = [NSURL URLWithString:@"http://tupian.enterdesk.com/uploadfile/2014/1126/20141126102508269.jpg"];        //计算机只能识别存储二进制数据    //dataWithContentsOfURL    从一个URL地址加载一段数据(本地或者网上都可以);    NSData *data = [NSData dataWithContentsOfURL:url];    //imageWithData  将二进制数据转换为图片    UIImage *img =[UIImage imageWithData:data];        //修改UI的代码最好写在主线程中,否则容易出错    [self performSelectorOnMainThread:@selector(setImage:) withObject:img waitUntilDone:YES];        //将下载好的图片存入硬盘    [data writeToFile:[NSHomeDirectory()stringByAppendingPathComponent:@"Documents/MyPic.jpg"] atomically:YES];}- (void)setImage:(UIImage *)img{    _imgView.image = img;}


7 0
原创粉丝点击