ios5CookBook学习笔记之异步加载网络图片

本文介绍了一种在iOS应用中实现图片异步加载的方法。通过使用GCD(Grand Central Dispatch)来分配任务到后台线程进行图片下载,并确保在主线程更新UI。此过程包括从网络获取图片数据、解析为UIImage对象并显示在UIImageView中。

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

 dispatch_queue_t mainQueue=dispatch_get_main_queue();//获取主队列


 //从网络上加载一幅图片
    dispatch_queue_t currentQueue=dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);//第一个参数表明在此队列获取的时间片
    //异步加载
    dispatch_async(currentQueue, ^(void){
        __block UIImage *image=nil;
        //在次级线程中同步加载
        dispatch_sync(currentQueue, ^{
            NSString *stringAsUrl=@"http://ww3.sinaimg.cn/bmiddle/7f4aad6djw1dyhxfs9mt3j.jpg";
            NSURL *url=[NSURL URLWithString:stringAsUrl];
            NSURLRequest *request=[NSURLRequest requestWithURL:url];
            NSError *downLoadError=nil;
            NSData *imageData=[NSURLConnection sendSynchronousRequest:request returningResponse:nil error:&downLoadError];//发送网络请求
            
            if (downLoadError==nil&&imageData!=nil) {
                image=[UIImage imageWithData:imageData];
            }
            else if(downLoadError!=nil)
            {
                NSLog(@"error With %@",downLoadError);
            }
            else
                NSLog(@"所提供的url中没有图片");
       });
        //加载完成后,返回至主线程
        dispatch_sync(mainQueue, ^{
            if (image!=nil) {
                UIImageView *imageView=[[UIImageView alloc]initWithFrame:self.view.bounds];
                [imageView setImage:image];
                [self.view addSubview:imageView];
            }
            else
                NSLog(@"照片下载失败");
        });
    });

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值