源码下载地址:http://download.youkuaiyun.com/detail/robinson_911/9631415
截图:
码
一. NSURL异步连接(delegate)
// 1.设置请求路径
NSURL *url = [NSURLURLWithString:requestPNGUrl];
// 2.创建请求对象
NSMutableURLRequest *mutablerequest = [[NSMutableURLRequestalloc]initWithURL:urlcachePolicy:NSURLRequestReloadIgnoringLocalCacheDatatimeoutInterval:15];
mutablerequest.HTTPMethod =@"GET";//请求方式,默认GET
// 3.发送请求
[NSURLConnectionconnectionWithRequest:mutablerequestdelegate:self];
4. 代理实现
//异步连接(代理)
//设置NSURLConnection代理
//实现相应的代理方法:开始响应接受数据、接收数据 、成功、失败
#pragma mark -- NSURLConnectionDataDelegate
//收到服务器回应的时候此方法会被调用
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
NSLog(@"已经接收到的响应%@",response);
}
//每次接收到服务器传输数据的时候调用,此方法根据数据大小会被调用多次
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
//NSLog(@"已经接收到的数据%s",__FUNCTION__);
[self.recieveData appendData:data];
}
//数据传输完成以后调用此方法,此方法中得到最终的数据recieveData
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSLog(@"数据接收完毕%s",__FUNCTION__);
NSLog(@"已经接收到的数据长度%lu字节",(unsigned long)self.recieveData.length);
[self showNetWorkImage];//数据接收完毕,刷新界面,显示图片
}
#pragma mark -- NSURLConnectionDelegate
//网络请求中,出现任何错误(断网,链接超时等)会进入此方法
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(@"数据接收失败,产生错误%s",__FUNCTION__);
NSLog(@"数据接收失败,产生错误%@",error);
}
二. NSURL block方式下载图片
//异步连接(block)
- (void)sendAsynRequestByBlockForImage
{
// 1.设置请求路径
NSURL *url = [NSURL URLWithString:requestUrl];
// 2.创建请求对象
NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:15];
// 3.发送请求
//如果数据接收完毕,data为接收到的数据。如果出错,那么错误信息保存在error中。
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue ] completionHandler: ^(NSURLResponse *response, NSData *data, NSError * connectionError)
{
if (response)
{
NSLog(@"已经接收到的响应%@",response);
}
if (data.length > 0)
{
[self.recieveData appendData:data];
NSString * resultsString = [[NSString alloc] initWithData:self.recieveData encoding:NSUTF8StringEncoding];
NSLog(@"receive data %@",resultsString);
[self showNetWorkImage];
}
NSLog(@"已经接收到的数据长度%lu字节",(unsigned long)self.recieveData.length);
if (connectionError)
{
NSLog(@"错误原因%@",connectionError);
}
}
];
}