859
技術社區[雲棲]
iOS開發那些事-iOS網絡編程異步GET方法請求編程
上篇博客提到同步請求,同步請求用戶體驗不好,並且介紹了在同步方法上實現異步,事實上iOS SDK也提供了異步請求的方法。異步請求會使用NSURLConnection委托協議NSURLConnectionDelegate。在請求不同階段會回調委托對象方法。NSURLConnectionDelegate協議的方法有:
connection:didReceiveData: 請求成功,開始接收數據,如果數據量很多,它會被多次調用;
connection:didFailWithError: 加載數據出現異常;
connectionDidFinishLoading: 成功完成加載數據,在connection:didReceiveData方法之後執行;
使用異步請求的主視圖控製器MasterViewController.h代碼如下:
#import <UIKit/UIKit.h> #import “NSString+URLEncoding.h” #import “NSNumber+Message.h” @interface MasterViewController : UITableViewController <NSURLConnectionDelegate> @property (strong, nonatomic) DetailViewController *detailViewController; //保存數據列表 @property (nonatomic,strong) NSMutableArray* listData; //接收從服務器返回數據。 @property (strong,nonatomic) NSMutableData *datas; //重新加載表視圖 -(void)reloadView:(NSDictionary*)res; //開始請求Web Service -(void)startRequest; @end
上麵的代碼在MasterViewController定義中實現了NSURLConnectionDelegate協議。datas屬性用來存放從服務器返回的數據,定義為可變類型,是為了從服務器加載數據過程中不斷地追加到這個datas中。MasterViewController.m代碼如下:
/* * 開始請求Web Service */ -(void)startRequest { NSString *strURL = [[NSString alloc] initWithFormat: @”https://iosbook3/mynotes/webservice.php?email=%@&type=%@&action=%@”, @”<你的iosbook1.com用戶郵箱>”,@”JSON”,@”query”]; NSURL *url = [NSURL URLWithString:[strURL URLEncodedString]]; NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url]; NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self]; if (connection) { _datas = [NSMutableData new]; } } #pragma mark- NSURLConnection 回調方法 - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { ① [_datas appendData:data]; } -(void) connection:(NSURLConnection *)connection didFailWithError: (NSError *)error { NSLog(@”%@”,[error localizedDescription]); } - (void) connectionDidFinishLoading: (NSURLConnection*) connection { ② NSLog(@”請求完成…”); NSDictionary* dict = [NSJSONSerialization JSONObjectWithData:_datas options:NSJSONReadingAllowFragments error:nil]; [self reloadView:dict]; }
在第①行的connection:didReceiveData:方法中,通過[_datas appendData:data]語句不斷地接收服務器端返回的數據,理解這一點是非常重要的。如果加載成功就回調第②行的connectionDidFinishLoading:方法,這個方法被回調也意味著這次請求的結束,這時候_datas中的數據是完整的,在這裏把數據發送回表示層的視圖控製器。
最後更新:2017-04-03 21:30:14