異步要求使用與同步和隊(duì)列式異步要求相同的對(duì)象,只不過(guò)又增加了另外一個(gè)對(duì)象,即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];
}
/*
*如果協(xié)議處理器接收到來(lái)自服務(wù)器的重定向要求,就會(huì)調(diào)用該方法
*/
-(NSURLRequest *)connection:(NSURLConnection *)connection willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response{
// NSLog(@"All Headers = %@", [(NSHTTPURLResponse *) response allHeaderFields]);
return request;
}
/*
*當(dāng)協(xié)議處理器接收到足夠的數(shù)據(jù)來(lái)創(chuàng)建URL響應(yīng)對(duì)象時(shí)會(huì)調(diào)用didReceiveResponse方法。如果在接收到足夠的數(shù)據(jù)來(lái)構(gòu)建對(duì)象前出現(xiàn)了毛病,
*就不會(huì)調(diào)用該方法
*/
-(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;
}
}
/*
*當(dāng)協(xié)議處理器接收到部份或全部響應(yīng)體時(shí)會(huì)調(diào)用該方法。該方法可能不會(huì)調(diào)用,也可能調(diào)用屢次,并且調(diào)用總是跟在最初的connection:didReceiveResponse以后
*/
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
totalDownLoaded += [data length];
NSLog(@"%ld", (long)totalDownLoaded);
}
/*
*當(dāng)連接失敗時(shí)會(huì)調(diào)用這個(gè)拜托方法。該方法可能會(huì)在要求處理的任何階段得到調(diào)用
*/
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
NSLog(@"netWork connect error");
}
/*
*當(dāng)全部要求完成加載并且接收到的所有數(shù)據(jù)都被傳遞給拜托后,就會(huì)調(diào)用該拜托方法
*/
-(void)connectionDidFinishLoading:(NSURLConnection *)connection{
NSLog(@"Finish");
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end