2017-11-28 1 views
0

저는 몇 달 동안 objective-C를 배웠습니다. 그 시간에 나는 기본적인 게시물 요청을 할 수 있었지만, 오늘 중첩 된 사전을 포함하는 게시물 요청 헤더를 보았습니다. 이러한 API에 데이터를 전달하는 방법을 잘 모르겠습니다.Objective-C 헤더에 중첩 된 사전이있는 Http Post 요청에 데이터를 보내는 방법

제 질문은 어떻게하면이 API에 데이터를 게시 할 수 있습니까? 복잡한 API 요청이나 답변을 제공하는 예제와 관련있는 독서 자료 및 자습서를 가리켜 주시면 감사하겠습니다.

이 API 헤더는 다음과 같습니다

{ "header": 
 
    { "id": "2312b24c-5b83-46f0-8670-5edc2b1d1672", 
 
    "parentId": "3gyy-w325e-bebd-ddsfsdf", 
 
    "countryCode": "IRELAND", 
 
    "timestamp": "2017-10-13T08:39:14.638Z" }, 
 
    "myinfo": 
 
    { "User": "intro", 
 
    "contactPerson": "Newbee", 
 
    "contact": "00000000", 
 
    "notes": "hey guys i am new" 
 
     
 
    } 
 
    
 
}

이 내가 여러 사전 도움이 필요 내 코드입니다.

__block NSMutableDictionary *resultsDictionary; 
     SMAMobileAPI *api = [SMAMobileAPI sharedSMAMobileAPI]; 
     NSMutableDictionary *bodyParams = [[NSMutableDictionary alloc]init]; 

     NSMutableDictionary *header = [[NSMutableDictionary alloc]init]; 
     [header setValue:@"2312b23c-5b83-46f0-8670-5edc2b1d1672" forKey:@"id"]; 
     [header setValue:@"2e3a015e-bebd-ddsfsdf" forKey:@"parentId"]; 
     [header setValue:@“IRELAND" forKey:@"countryCode"]; 
     [header setValue:@"2017-10-13T08:39:14.638Z" forKey:@"timeStamp"]; 

     NSMutableDictionary *myinfo = [[NSMutableDictionary alloc]init]; 
     [Case setValue:@“intro" forKey:@“User"]; 
     [Case setValue:@“newbie" forKey:@"contactPerson"]; 
     [Case setValue:@"+254 724474140" forKey:@"contactPersonNo"]; 
     [Case setValue:@"iOS case" forKey:@"notes"]; 

     [bodyParams setValue:header forKey:@"header"]; 
     [bodyParams setValue:myinfo forKey:@“myinfo"]; 

    if ([NSJSONSerialization isValidJSONObject:bodyParams]) {//validate it 
     NSError* error = nil; 
     NSData* jsonData = [NSJSONSerialization dataWithJSONObject:bodyParams options:NSJSONWritingPrettyPrinted error: &error]; 
     NSString *jsonString = [[NSString alloc] initWithData:jsonData 
encoding:NSUTF8StringEncoding]; 
     NSURL* url = [NSURL URLWithString:@“my URL"]; 
     NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30.0]; 
     [request setHTTPMethod:@"POST"];//use POST 
     [request setValue:@"application/json" forHTTPHeaderField:@"Accept"]; 
     [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"]; 
     [request setValue:[NSString stringWithFormat:@"%lu",(unsigned long)[jsonData length]] forHTTPHeaderField:@"Content-length"]; 
     [request setHTTPBody:jsonData];//set data 
     __block NSError *error1 = nil; 

     //use async way to connect network 
     [NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse* response,NSData* data,NSError* error) 
     { 
      if ([data length]>0 && error == nil) { 
       resultsDictionary = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&error1]; 
       NSLog(@"resultsDictionary is %@",resultsDictionary); 
       [self hideLoading]; 

      } else if ([data length]==0 && error ==nil) { 
       NSLog(@" download data is null"); 
       [self hideLoading]; 
      } else if(error!=nil) { 
       NSLog(@" error is %@",error); 
       [self hideLoading]; 
      } 
     }]; 
    } 
} 
+0

AFNetworking은 Objective-C를 쉽게 만듭니다. https://stackoverflow.com/questions/21487184/posting-json-data-using-afnetworking-2-0을 참조하십시오. – Mick

+0

제안 해 주셔서 감사합니다. 그러나 저는 아직이 언어에 익숙하지 않으며, 도서관으로 옮기기 전에 기본 방식으로하는 방법을 알고 싶습니다. – kudzi

+0

유효한 요청입니다. 카운터 제안 : Objective-C로 간단한 GET 요청을하려고하면 네이티브 네트워킹을 다룰 가치가 없다는 것을 알 수 있습니다. – Mick

답변

1

NSDictionary를 JSON으로 변환하는 것이 실제 문제입니다. 설명서를 참조하십시오 https://developer.apple.com/documentation/foundation/jsonserialization

NSData *jsonData = [NSJSONSerialization dataWithJSONObject:yourDictionary 
    options:NSJSONWritingPrettyPrinted error:&error]; 
NSString *jsonString = [[NSString alloc] initWithData:jsonData 
    encoding:NSUTF8StringEncoding]; 
+0

고마워 @Mick하지만 난 또한이 부분을 찾고있다 NSDictionary * dict = @ {@ "key": value}; 해당 헤더에서 사전 또는 중첩 된 사전을 만드는 것은 내가 도와야 할 첫 번째 부분입니다. 도와 주셔서 감사합니다 – kudzi

+0

이 마음에 드십니까? * dict = @ {@ "@"key ": nestedKey": nestedValue}} – Mick

+0

구현하고 u로 돌아 가기 – kudzi

관련 문제