// 将容器初始化
_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];
}