19
20

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

API通信を書きたいときに見るメモ

Last updated at Posted at 2014-03-14

API通信前後の処理について、忘備用メモです。

#環境
iOS7(Xcode5、iPad、iPadAir)
MacBookAir

#呼び出し方
##GETメソッド/クエリ文字列 

NSURL *url;
NSMutableURLRequest *request;

//URL作成
url     = [NSURL URLWithString: [NSString stringWithFormat:@"http://XXXXXXXX req_param=%@",@"user01"]];

//リクエスト作成
request = [NSMutableURLRequest requestWithURL:url];

//HTTPリクエスト送信
NSHTTPURLResponse *response = nil;
NSError *error          = nil;
NSData *result          = [NSURLConnection sendSynchronousRequest:request
                                                  returningResponse:&response
                                                              error:&error];

##POSTメソッド

NSURL *url;
NSMutableURLRequest *request;

//パラメータの組み立て
NSMutableDictionary *mutableDic = [NSMutableDictionary dictionary];
  //★APIの形式に合わせて組み立てる
[mutableDic setValue:user_id forKey:@"user_id"];
  //★入れ子の場合は配列のオブジェクトなどをそのまま格納できる
[mutableDic setValue:answers forKey:@"answers"];
NSData *body    = [NSJSONSerialization dataWithJSONObject:mutableDic options:NSJSONWritingPrettyPrinted error:Nil];

//リクエスト作成
url     = [NSURL URLWithString:@"http://XXXXXXXX"];
request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10.0];
[request setHTTPMethod:@"POST"];
[request setHTTPBody:body];

//HTTPリクエスト送信
NSHTTPURLResponse *response = nil;
NSError *error          = nil;
NSData *result          = [NSURLConnection sendSynchronousRequest:request
                                                  returningResponse:&response
                                                              error:&error];


#レスポンスを扱うには
##HTTPステータスコードの取得

int statusCode = [response statusCode];

##エラーコードの取得

int errorCode = error.code;

##JSONをパース

NSError *perthError     = nil;
NSDictionary *resultDic = [NSJSONSerialization JSONObjectWithData:result options:0 error:&perthError];
19
20
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
19
20

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?