图片下载保存显示

将图片下载好保存到沙盒,然后主线程中刷新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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值