网络请求的格式大体上分为两种:第一种是同步请求,弊端是在进行大数据加载的时候会有卡顿现象。
第二种是异步请求:优化了同步请求,没有卡顿现象,而且提高了效率。
1.同步请求的步骤:
1)创建URL。
2)封装请求
3)发起连接请求,接收数据
//同步请求
//1 创建 url
NSURL *url = [NSURL URLWithString:URL];
//2 创建一个请求
NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:20];
//3 建立连接,获取数据
NSURLResponse *response = nil;
NSError *error = nil;
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
2.异步请求:异步请求是对数据的分批接受。需要调用 NSURLConnectionDataDelegate和NSURLConnectionDelegate 代理方法进行数据的处理。
步骤和同步处理大致相同,最后一步设置了代理。
NSURL *aSyURL = [NSURL URLWithString:URL];
NSURLRequest *aSyRequest = [NSURLRequest requestWithURL:aSyURL cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:20];
[NSURLConnection connectionWithRequest:aSyRequest delegate:self];
NSLog(@"data1:%@",self.data);
1)NSURLConnectionDataDelegate 方法
//------------
//- (NSURLRequest *)connection:(NSURLConnection *)connection willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response
//{
// NSLog(@"即将发送请求");
// //Sent when the connection determines that it must change URLs in order to continue loading a request.
// return nil;
//}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
self.data = [NSMutableData dataWithCapacity:20]; //创建缓存
NSLog(@"接收到相应");
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
NSLog(@"确认收到数据");
[self.data appendData:data];
}
- (NSInputStream *)connection:(NSURLConnection *)connection needNewBodyStream:(NSURLRequest *)request
{
NSLog(@"needNewBodyStream");
return nil;
}
- (void)connection:(NSURLConnection *)connection didSendBodyData:(NSInteger)bytesWritten
totalBytesWritten:(NSInteger)totalBytesWritten
totalBytesExpectedToWrite:(NSInteger)totalBytesExpectedToWrite
{
}
- (NSCachedURLResponse *)connection:(NSURLConnection *)connection willCacheResponse:(NSCachedURLResponse *)cachedResponse
{
return nil;
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSLog(@"结束下载");
NSLog(@"data1:%@",self.data);
}
2)NSURLConnectionDelegate 主要调用的是查询失败的的method
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(@"error:%@",[error localizedFailureReason]);
}