IOS非同期GETメソッドリクエスト
3702 ワード
1.プロトコルNSURLConnectionDelegateの追加
2.ヘッダファイル「NSString+URLEncoding」を導入し、URLを処理して符号化する.
3.サーバから返信されたメッセージコードをユーザが理解できるメッセージに変換するヘッダファイル「NSNumber+Message」を導入する.
4.サーバから返されたデータを格納するNSMutableDataタイプのdatasを宣言する
5.NSMutableArrayタイプのlistDataを宣言し、データリストを保存する
6.DetailViewControllerコントローラタイプを宣言するdetailViewController
7.関数-(void)startRequest、Webサービスのリクエスト開始
8.NSURLConnectionコールバック方法
9.テーブルビューの再ロード
2.ヘッダファイル「NSString+URLEncoding」を導入し、URLを処理して符号化する.
3.サーバから返信されたメッセージコードをユーザが理解できるメッセージに変換するヘッダファイル「NSNumber+Message」を導入する.
4.サーバから返されたデータを格納するNSMutableDataタイプのdatasを宣言する
5.NSMutableArrayタイプのlistDataを宣言し、データリストを保存する
6.DetailViewControllerコントローラタイプを宣言するdetailViewController
7.関数-(void)startRequest、Webサービスのリクエスト開始
-(void)startRequest
{
NSString *strURL = [[NSString alloc] initWithFormat:
@"http://iosbook3.com/service/mynotes/webservice.php?email=%@&type=%@&action=%@",
@"< iosbook3.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];
}
}
8.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];
}
9.テーブルビューの再ロード
-(void)reloadView:(NSDictionary*)res
{
NSNumber *resultCodeObj = [res objectForKey:@"ResultCode"];
if ([resultCodeObj integerValue] >=0)
{
self.listData = [res objectForKey:@"Record"];
[self.tableView reloadData];
} else {
NSString *errorStr = [resultCodeObj errorMessage];
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@" "
message:errorStr
delegate:nil
cancelButtonTitle:@"OK"
otherButtonTitles: nil];
[alertView show];
}