iOS開發那些事-iOS網路程式設計非同步GET方法請求程式設計

智捷關東昇發表於2013-03-27

上篇部落格提到同步請求,同步請求使用者體驗不好,並且介紹了在同步方法上實現非同步,事實上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:

@”http://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中的資料是完整的,在這裡把資料傳送回表示層的檢視控制器。

相關文章