80

私はobjective-cが初めてで、最近リクエスト/レスポンスに多大な努力を払い始めています。URLを(http GET経由で)呼び出して、返されたjsonを解析できる実用的な例があります。

これの実際の例は以下のとおりです

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    [responseData setLength:0];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    [responseData appendData:data];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
  NSLog([NSString stringWithFormat:@"Connection failed: %@", [error description]]);
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    [connection release];
  //do something with the json that comes back ... (the fun part)
}

- (void)viewDidLoad
{
  [self searchForStuff:@"iPhone"];
}

-(void)searchForStuff:(NSString *)text
{
  responseData = [[NSMutableData data] retain];
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.whatever.com/json"]];
    [[NSURLConnection alloc] initWithRequest:request delegate:self];
}

私の最初の質問は、このアプローチはスケールアップしますか? それとも、これは非同期ではありませんか (つまり、アプリが応答を待っている間、UI スレッドをブロックします)

2 番目の質問は、GET の代わりに POST を実行するように、このリクエスト部分を変更するにはどうすればよいですか? HttpMethod をそのように変更するだけですか?

[request setHTTPMethod:@"POST"];

そして最後に、一連のjsonデータをこの投稿に単純な文字列として追加するにはどうすればよいですか(たとえば)

{
    "magic":{
               "real":true
            },
    "options":{
               "happy":true,
                "joy":true,
                "joy2":true
              },
    "key":"123"
}

前もって感謝します

4

8 に答える 8

105

これが私がすることです(私のサーバーに行くJSONは、key = question..ie {:question => {dictionary}}の1つの値(別の辞書)を持つ辞書である必要があることに注意してください):

NSArray *objects = [NSArray arrayWithObjects:[[NSUserDefaults standardUserDefaults]valueForKey:@"StoreNickName"],
  [[UIDevice currentDevice] uniqueIdentifier], [dict objectForKey:@"user_question"],     nil];
NSArray *keys = [NSArray arrayWithObjects:@"nick_name", @"UDID", @"user_question", nil];
NSDictionary *questionDict = [NSDictionary dictionaryWithObjects:objects forKeys:keys];

NSDictionary *jsonDict = [NSDictionary dictionaryWithObject:questionDict forKey:@"question"];

NSString *jsonRequest = [jsonDict JSONRepresentation];

NSLog(@"jsonRequest is %@", jsonRequest);

NSURL *url = [NSURL URLWithString:@"https://xxxxxxx.com/questions"];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
             cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];


NSData *requestData = [jsonRequest dataUsingEncoding:NSUTF8StringEncoding];

[request setHTTPMethod:@"POST"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setValue:[NSString stringWithFormat:@"%d", [requestData length]] forHTTPHeaderField:@"Content-Length"];
[request setHTTPBody: requestData];

NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:request delegate:self];
if (connection) {
 receivedData = [[NSMutableData data] retain];
}

次に、receivedDataは次のように処理されます。

NSString *jsonString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSDictionary *jsonDict = [jsonString JSONValue];
NSDictionary *question = [jsonDict objectForKey:@"question"];

これは100%明確ではなく、再読する必要がありますが、開始するにはすべてがここにあるはずです。そして私が言えることから、これは非同期です。これらの呼び出しが行われている間、UIがロックされません。お役に立てば幸いです。

于 2010-12-17T01:11:38.830 に答える
7

私はしばらくこれに苦労しました。サーバー上で PHP を実行します。このコードはjsonを投稿し、サーバーからjson応答を取得します

NSURL *url = [NSURL URLWithString:@"http://example.co/index.php"];
NSMutableURLRequest *rq = [NSMutableURLRequest requestWithURL:url];
[rq setHTTPMethod:@"POST"];
NSString *post = [NSString stringWithFormat:@"command1=c1&command2=c2"];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding];
[rq setHTTPBody:postData];
[rq setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
NSOperationQueue *queue = [[NSOperationQueue alloc] init];

[NSURLConnection sendAsynchronousRequest:rq queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
 {
     if ([data length] > 0 && error == nil){
         NSError *parseError = nil;
         NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:&parseError];
         NSLog(@"Server Response (we want to see a 200 return code) %@",response);
         NSLog(@"dictionary %@",dictionary);
     }
     else if ([data length] == 0 && error == nil){
         NSLog(@"no data returned");
         //no data, but tried
     }
     else if (error != nil)
     {
         NSLog(@"there was a download error");
         //couldn't download

     }
 }];
于 2015-02-11T15:03:26.067 に答える
6

ASIHTTPRequestを使用することをお勧めします

ASIHTTPRequest は、CFNetwork API の使いやすいラッパーであり、Web サーバーとの通信のいくつかの面倒な側面を簡単にします。Objective-C で書かれており、Mac OS X と iPhone アプリケーションの両方で動作します。

基本的な HTTP リクエストを実行し、REST ベースのサービス (GET / POST / PUT / DELETE) と対話するのに適しています。含まれている ASIFormDataRequest サブクラスにより、multipart/form-data を使用して POST データとファイルを簡単に送信できます。


元の作成者がこのプロジェクトを中止したことに注意してください。理由と代替手段については、次の投稿を参照してください: http://allseeing-i.com/%5Brequest_release%5D ;

個人的にはAFNetworkingの大ファンです

于 2010-12-16T02:33:55.710 に答える
3

ほとんどの人はすでにこれを知っていますが、念のためにこれを投稿します.

iOS6 以降では、高速で「外部」ライブラリを含めることに依存しないNSJSONSerialization クラスがあります。

NSDictionary *result = [NSJSONSerialization JSONObjectWithData:[resultStr dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil]; 

これは、iOS6 以降で JSON を効率的に解析できるようになった方法です。SBJson の使用も ARC 実装前であり、ARC 環境で作業している場合、これらの問題ももたらします。

これが役立つことを願っています!

于 2013-11-12T14:49:47.460 に答える
2

Restkitを使用した素晴らしい記事はこちら

ネストされたデータを JSON にシリアライズし、そのデータを HTTP POST リクエストにアタッチする方法について説明します。

于 2013-08-19T16:34:57.760 に答える
2

コードを近代化するために Mike G の回答を編集したため、3 対 2 で拒否されました。

この編集は、投稿の作成者に対処することを目的としており、編集としては意味がありません. コメントまたは回答として書かれているはずです

ここで別の回答として編集を再投稿しています。この編集により、Rob の 15 票のコメントが示唆するように、JSONRepresentation依存関係が削除されます。NSJSONSerialization

    NSArray *objects = [NSArray arrayWithObjects:[[NSUserDefaults standardUserDefaults]valueForKey:@"StoreNickName"],
      [[UIDevice currentDevice] uniqueIdentifier], [dict objectForKey:@"user_question"],     nil];
    NSArray *keys = [NSArray arrayWithObjects:@"nick_name", @"UDID", @"user_question", nil];
    NSDictionary *questionDict = [NSDictionary dictionaryWithObjects:objects forKeys:keys];

    NSDictionary *jsonDict = [NSDictionary dictionaryWithObject:questionDict forKey:@"question"];

    NSLog(@"jsonRequest is %@", jsonRequest);

    NSURL *url = [NSURL URLWithString:@"https://xxxxxxx.com/questions"];

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
                 cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];


    NSData *requestData = [NSJSONSerialization dataWithJSONObject:dict options:0 error:nil]; //TODO handle error

    [request setHTTPMethod:@"POST"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [request setValue:[NSString stringWithFormat:@"%d", [requestData length]] forHTTPHeaderField:@"Content-Length"];
    [request setHTTPBody: requestData];

    NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:request delegate:self];
    if (connection) {
     receivedData = [[NSMutableData data] retain];
    }

receivedData は次のように処理されます。

NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
    NSDictionary *question = [jsonDict objectForKey:@"question"];
于 2015-11-03T17:54:46.447 に答える
0

json文字列を送信するためにこのコードを試すことができます

NSData *jsonData = [NSJSONSerialization dataWithJSONObject:ARRAY_CONTAIN_JSON_STRING options:NSJSONWritin*emphasized text*gPrettyPrinted error:NULL];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSString *WS_test = [NSString stringWithFormat:@"www.test.com?xyz.php&param=%@",jsonString];
于 2016-10-04T12:28:52.567 に答える