2014年3月19日水曜日

ios 同期通信でpostする

iosで同期通信でpostします。

いきなりcodeです。

     
    // Send a synchronous request
    NSURL *url = [NSURL URLWithString:@"url名"];
    // post情報をくっつけるので、NSMutableURLRequestを使用
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    // Set the method(HTTP-POST)
    [request setHTTPMethod:@"POST"];
    // Set the request-body.
    NSString *reqBody = [NSString stringWithFormat:@"login[account]=%@&login[password]=%@",account名,password];
    // utf8にする
    [request setHTTPBody:[reqBody dataUsingEncoding:NSUTF8StringEncoding]];
    
    // 吐き出すエラー
    NSError * error = nil;
    NSURLResponse* response = nil;
    
    
    
    NSData* data = [NSURLConnection sendSynchronousRequest:request
                                          returningResponse:&response
                                                      error:&error];
    // 通信が行なわれた後に実行されます。
   // 電波が悪く通信できなかった(errorStringにinternet can't useとかデル)
    NSString *errorString = [error localizedDescription];
    if(0 < [errorString length])
    {
       // error処理
    }
    // 通信成功
    else
    {
       // utf8で返った情報をとってくる
       NSString *result = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
       // jsonデーターをとってこよう
       NSDictionary* jsonObj = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];
       // 返った情報を表示
       NSLog(@"result: %@", result);
    }


解説は、コメントに書いたので、特にないっすね。

0 件のコメント:

コメントを投稿