异步要求使用与同步和队列式异步要求相同的对象,只不过又增加了另外一个对象,即NSURLConnectionDelegate:
上代码:
#import "ViewController.h"
NSInteger totalDownLoaded = 0;
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
NSURL *url = [NSURL URLWithString:@"http://www.example.com/test.php"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
NSURLConnection *conn = [NSURLConnection connectionWithRequest:request delegate:self];
[conn start];
}
/*
*如果协议处理器接收到来自服务器的重定向要求,就会调用该方法
*/
-(NSURLRequest *)connection:(NSURLConnection *)connection willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response{
// NSLog(@"All Headers = %@", [(NSHTTPURLResponse *) response allHeaderFields]);
return request;
}
/*
*当协议处理器接收到足够的数据来创建URL响应对象时会调用didReceiveResponse方法。如果在接收到足够的数据来构建对象前出现了毛病,
*就不会调用该方法
*/
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
NSLog(@"All Headers = %@", [httpResponse allHeaderFields]);
NSLog(@"statusCode = %ld", (long)httpResponse.statusCode);
if (httpResponse.statusCode != 200) {
[connection cancel];
return;
}
}
/*
*当协议处理器接收到部份或全部响应体时会调用该方法。该方法可能不会调用,也可能调用屡次,并且调用总是跟在最初的connection:didReceiveResponse以后
*/
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
totalDownLoaded += [data length];
NSLog(@"%ld", (long)totalDownLoaded);
}
/*
*当连接失败时会调用这个拜托方法。该方法可能会在要求处理的任何阶段得到调用
*/
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
NSLog(@"netWork connect error");
}
/*
*当全部要求完成加载并且接收到的所有数据都被传递给拜托后,就会调用该拜托方法
*/
-(void)connectionDidFinishLoading:(NSURLConnection *)connection{
NSLog(@"Finish");
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end