イナヅマTVログ

Objective-C事始め – サーバーリクエスト:XMLを送信してXMLを取得する

| 1件のコメント

2013-08の書きかけの記事の再編集投稿です。
Xcode 4.6.3, iOS 6 当時の情報になります。

REST風な通信をObjective-Cでの巻き。
wikipedia: REST

良くわかってないけど。。。
XML送信してXML受信する感じって思ってる。

- (id) requestWithURL:(NSURL *)urlWithString parameterWithString:(NSString *)parameterWithString didFailWithError:(NSError **)didFailWithError
{
    // URLRequest
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:urlWithString];
    // set header XML
    [request setValue:@"application/xml" forHTTPHeaderField:@"Content-type"];
    // set POST
    [request setHTTPMethod:@"POST"];
    // set XML to body
    [request setHTTPBody:[parameterWithString dataUsingEncoding:NSUTF8StringEncoding]];
    // response(結果)
    NSHTTPURLResponse *response = nil;
    // error
    NSError *error = nil;
 
    // 戻り値, 送信
    NSData *data = [NSURLConnection sendSynchronousRequest:request
                                         returningResponse:&response
                                                     error:&error];
 
    // error
    if (error)
    {
        data = nil;
        NSString *errorMessage = [NSString stringWithFormat:@"サーバ通信エラー {%ld}", (long)error.code];
 
        NSDictionary *info = nil;
        if (error.localizedDescription == nil) {
            info = @{NSLocalizedDescriptionKey: errorMessage};
        } else {
            info = @{NSLocalizedDescriptionKey: errorMessage,
                     NSLocalizedRecoverySuggestionErrorKey: error.localizedDescription};
        }
 
        *didFailWithError = [[NSError alloc] initWithDomain:@"com.example.applicationname" code:123 userInfo:info];
    }
 
    return data;
}

errorが無かったらXMLが返ってきて後はパースする予定。

1件のコメント

  1. ピンバック: Objective-C事始め - XMLをパースしてNSDictionaryへ « イナヅマTVログ

コメントを残す

必須欄は * がついています


このサイトはスパムを低減するために Akismet を使っています。コメントデータの処理方法の詳細はこちらをご覧ください