異步要求使用與同步和隊列式異步要求相同的對象,只不過又增加了另外一個對象,即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