您的位置:首页 > 理论基础 > 计算机网络

UI 网络请求协议 NSURLConnectionDataDelegate

2015-08-12 11:22 561 查看
// 将容器初始化

_webData =[[NSMutableDataalloc]initWithCapacity:0];

// 请求体

NSURLRequest*request=[[NSURLRequestalloc]initWithURL:[NSURLURLWithString:kImageURLString]];

_connection =[[NSURLConnectionalloc]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=[[UIImageViewalloc]initWithFrame:CGRectZero];

image.center=self.view.center;

image.image=[UIImageimageWithData:_webData];

[self.viewaddSubview:image];

[UIViewanimateWithDuration:2animations:^{

image.frame=self.view.bounds;

[image setYOffset:64];

}];

[image release];

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: