连接方式有两种:同步和异步。
同步连接:1. 使用sendSynchronousRequest:requestreturningResponse:&response error:&error方法。2.同步连接会出现出现卡死的现象,用户交互不好,影响用户体验。
宏定义一个网址#define kURL@"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx?date=20131129&startRecord=1&len=5&udid=1234567890&terminalType=Iphone&cid=213"
下面的是一个同步的GET请求
NSURL * url= [NSURL URLWithString:kURL];
NSURLRequest* request = [NSURLRequest requestWithURL:url cachePolicy:(NSURLRequestUseProtocolCachePolicy) timeoutInterval:100 ];
NSURLResponse* response = nil;
NSError* error = nil;
NSData* data = [NSURLConnection sendSynchronousRequest:requestreturningResponse:&response error:&error ];
NSDictionary* dic = [NSJSONSerialization JSONObjectWithData:dataoptions:(NSJSONReadingMutableContainers)error:nil];
NSLog(@"%@",dic);
异步连接:1.异步连接可以分为两种。
Block 和delegate。
带Block的方法是 [ NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueuecurrentQueue] completionHandler:^(NSURLResponse *response, NSData*data, NSError *connectionError) {}];
该方法需要三个参数,分别表示如下含义:
request:请求;
queue:队列。一般情况下是CurrentQueue。
该方法将响应、数据、错误封装到了Blcok.
注意:Block中华的代码不会立即执行,只有当服务器请求完数据之后才会执行Block里面的代码。
面临问题:由于Block里面的代码不会立即执行,界面展示要比数据获取早,那当获取完数据之后如何通知界面呢。
NSURL * url= [NSURL URLWithString:kURL];
NSURLRequest* request = [NSURLRequest requestWithURL:url cachePolicy:(NSURLRequestUseProtocolCachePolicy) timeoutInterval:10];
[ NSURLConnection sendAsynchronousRequest:requestqueue:[NSOperationQueuecurrentQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError*connectionError) {
NSDictionary * dic =[NSJSONSerialization JSONObjectWithData:dataoptions:(NSJSONReadingMutableContainers)error:&connectionError];
NSLog(@"%@",dic);
//当数据使用完成之后,在Block里面重新导入数据
[self.tableView reloadData];
}];
带Delegate的异步连接
1.将数据下载进度封装到了协议中,所以一般情况下如果要显示下载进度会使用带Delegate的连接。
2.带Delegate的连接也是异步连接。界面要先显示出来之后才能获取到数据,所以面临的问题和Block面临的问题一致;
注意事项:代理中有一个方法名为
didReceiveData:该方法参数Data,不是已经下载的总Data,需要自己拼接Data数据
宏定义一个网址
#define mURL @"http://fdfs.xmcdn.com/group6/M03/3B/73/wKgDg1UxBYyCWoFZAHYGKdSPN90325.mp3"
网址内容是一段音频内容
#import "RootViewController.h"
#import
#define kURL @"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx?date=20131129&startRecord=1&len=5&udid=1234567890&terminalType=Iphone&cid=213"
#define mURL @"http://fdfs.xmcdn.com/group6/M03/3B/73/wKgDg1UxBYyCWoFZAHYGKdSPN90325.mp3"
@interface RootViewController ()<</span>NSURLConnectionDataDelegate>
{
long long _totalLength;//总长度}
}
@property(nonatomic,retain)NSMutableData * receivedData;//已经接收到的数据
@property(nonatomic,retain)UIProgressView * progressView;//进度条
@implementation RootViewController
-(void)dealloc
{
[_receivedDatarelease];
[_progressViewrelease];
[superdealloc];
}
-(NSMutableData *)receivedData
{
if (_receivedData == nil ){
self.receivedData = [NSMutableData dataWithCapacity:0];
}
return_receivedData;
}
-(UIProgressView *)progressView
{
if (_progressView == nil ){
self.progressView = [[[UIProgressView alloc]initWithProgressViewStyle:(UIProgressViewStyleDefault)]autorelease];
_progressView.frame = CGRectMake(30,300, 300, 30);
[self.view addSubview:_progressView];
}
return_progressView;
}
NSURL * url= [NSURL URLWithString:mURL];
NSURLRequest* request = [NSURLRequest requestWithURL:url cachePolicy:(NSURLRequestUseProtocolCachePolicy) timeoutInterval:15];
[[[NSURLConnection alloc]initWithRequest:requestdelegate:self]autorelease];//自带一个初始化方法,接收协议接收的是<</span>NSURLConnectionDataDelegate>这个协议
实现协议中的方法
//接收到服务器 响应
-(void)connection:(NSURLConnection *)connectiondidReceiveResponse:(NSURLResponse*)response
{
_totalLength= response.expectedContentLength;//总长度
NSLog(@"%lld",_totalLength);
}
//从服务器接收到数据
-(void)connection:(NSURLConnection *)connectiondidReceiveData:(NSData *)data
{
[self.receivedData appendData:data];//拼接Data
self.progressView.progress = 1.0 * self.receivedData.length / _totalLength;//读取进度
}
//数据获取完毕
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSError* error = nil;
AVAudioPlayer* player = [[AVAudioPlayer alloc]initWithData:self.receivedDataerror:&error];
if (error == nil ) {
[player prepareToPlay];
[player play];
}
else{
NSLog(@"%@",error);
}
}
//出现错误
-(void)connection:(NSURLConnection *)connectiondidFailWithError:(NSError*)error
{
NSLog(@"%@",[error localizedDescription]);
}