ios异步加载头像

该博客介绍了如何在iOS中异步加载网络头像图片,通过使用`dispatch_async`进行后台下载,然后将图片存储到沙盒中,最后在主线程更新UI,确保界面流畅。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

    //绘制一张图片
    _user_Image = [UIImage imageNamed:@"headImage.jpg"];
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^ {
        
        NSString *user_Image_UrlString = @"http://photo.l99.com/bigger/31/1363231021567_5zu910.jpg";
        NSURL *url = [NSURL URLWithString:[@"http://" stringByAppendingString:user_Image_UrlString ]];
        NSError *error = nil; 
        NSData* data = [NSData dataWithContentsOfURL:url options:0 error:&error];
        UIImage *imageStorage = [UIImage imageWithData:data];
        

        //存入沙盒
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
        NSString *filePath = [[paths objectAtIndex:0] stringByAppendingString:@"/userImage.jpg"];   // 保存文件的名称
        BOOL result = [UIImageJPEGRepresentation(imageStorage,1) writeToFile:filePath atomically:YES]; // 保存成功会返回YES
        
        UIImage *image = [UIImage imageWithContentsOfFile:filePath];
        
        dispatch_sync(dispatch_get_main_queue(), ^{
            
            if (image != nil) {
                _user_Image = image;
                [_tableView reloadData];
            }
        });
    });

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值