Objective-Cを1ヶ月で物にする、というミッション中なのでとにかく色々メモって行きます。
ということで、今回は並列的にHTTP通信(POST)する方法をメモ。
ケースとしては、一度APIを叩いてtokenをもらったのち、そのtokenを使って再度リクエストする、みたいなもの。
使用したクラスは以下。
- NSMutableURLRequest
- NSURL
- NSURLResponse
- NSData
- NSURLConnection
- NSDictionary
実際に動くサンプルは以下。
HTTP-Request-sample.m
//NSOperationQueueを使ってマルチスレッドでリクエスト
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[queue addOperationWithBlock:^{
//////////////////////////////////////
//APIからtokenを取得
//リクエスト用のパラメータを設定
NSString *user = @"user_name";
NSString *pass = @"password";
NSString *url = @"request_url";
NSString *param = [NSString stringWithFormat:@"url_name=%@&password=%@", user, pass];
//リクエストを生成
NSMutableURLRequest *request;
request = [[NSMutableURLRequest alloc] init];
[request setHTTPMethod:@"POST"];
[request setURL:[NSURL URLWithString:url]];
[request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
[request setTimeoutInterval:20];
[request setHTTPShouldHandleCookies:FALSE];
[request setHTTPBody:[param dataUsingEncoding:NSUTF8StringEncoding]];
//同期通信で送信
NSURLResponse *response = nil;
NSError *error = nil;
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
if (error != nil) {
NSLog(@"Error!");
return;
}
NSError *e = nil;
//取得したレスポンスをJSONパース
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:nil error:&e];
NSString *token = [dict objectForKey:@"token"];
NSLog(@"Token is %@", token);
//受け取ったtokenを付けて再度リクエスト
NSURL *url2 = [NSURL URLWithString:[NSString stringWithFormat:@"https://requst_url?token=%@", token]];
NSURLRequest *request2 = [NSURLRequest requestWithURL:url2];
NSURLResponse *response2 = nil;
NSError *error2 = nil;
NSData *data2 = [NSURLConnection sendSynchronousRequest:request2 returningResponse:&response2 error:&error2];
if (error2 != nil) {
NSLog(@"Error2!");
return;
}
NSError *e2 = nil;
NSDictionary *dict2 = [NSJSONSerialization JSONObjectWithData:data2 options:nil error:&e2];
NSLog(@"Response2: %@", response2);
NSLog(@"%@", dict2);
NSLog(@"%d", [dict2 count]);
}];