UI 网络请求协议 NSURLConnectionDataDelegate

本文介绍如何使用 Objective-C 中的 NSURLConnection 进行图片下载。文章详细解释了从初始化请求到处理响应数据的过程,并展示了如何将接收的数据转换为图片显示在界面上。

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

//    将容器初始化

    _webData =[[NSMutableData alloc]initWithCapacity:0];

    

//    请求体

    NSURLRequest*request=[[NSURLRequest alloc]initWithURL:[NSURL URLWithString:kImageURLString]];

    _connection =[[NSURLConnection alloc]initWithRequest:request delegate:self];


#pragma mark-NSURLConnectionDataDelegate

//链接失败的回调

-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error

{

    NSLog(@"链接发起失败%@",error);

}

//数据返回的回调

//当请求的数据总量非常大的时候,服务器会根据协议将数据压缩成数个小单元

//这个方法只要接收到小单元就会出现回调,所以这个方法可能会在一次请求调用多次

-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data

{

    NSLog(@"返回的数据%@",data);

}

//收到响应

-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response

{

    NSLog(@"response Header%@",[(NSHTTPURLResponse *) response allHeaderFields]);

    NSLog(@"response status %ld",[(NSHTTPURLResponse*) response statusCode]);

}

//请求完成

-(void)connectionDidFinishLoading:(NSURLConnection *)connection

{

   

    NSLog(@"请求完成!");

//    NSError *error=nil;

    /*

     NSJSONSerialization  原始数据

     NSJSONReadingMutbleContainers  转化成容器

     */

//    id object=[NSJSONSerialization JSONObjectWithData:_webData options:NSJSONReadingMutableContainers error:&error];

//    NSLog(@"%@ %@",[object class],object);

    UIImageView *image=[[UIImageView alloc]initWithFrame:CGRectZero];

    image.center=self.view.center;

    image.image=[UIImage imageWithData:_webData];

    [self.view addSubview:image];

    

    [UIView animateWithDuration:2 animations:^{

        image.frame=self.view.bounds;

        [image setYOffset:64];

    }];

    [image release];

    

}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值