2013-06-26 3 views
2

웹 API에서 JSON 요청을 잡으려고합니다. 서버에서 JSON 형식으로 응답을 받으면 NSDictionnary가 아닌 NSData 형식으로 응답을받습니다. 이 튜토리얼 http://www.raywenderlich.com/30445/afnetworking-crash-course# (RESTful 클래스 단락)에서 AFJSONRequestOperation에 의해 클라이언트의 등록 된 작업 클래스를 변경하여 무료 JSON 구문 분석을 할 수있게되었습니다. 그러나, 그것은 작동하지 않습니다, 나는 여전히 NSData 형식으로 응답을 얻을.AFNetworking을 사용한 JSON 구문 분석

편집 :

여기
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFData objectForKey:]: unrecognized selector sent to instance 0x753aa00' 

서버의 응답입니다 : 다음은 완전한 오류 메시지의

{"uid":"98545931","token":"98545931:176:ec0b862ba57fef88394950dd0cc41491"} 

누군가가 자동으로 해석 할 수없는 이유는 아이디어가 있습니까?

AFHTTPClient *client = [[AFHTTPClient alloc] initWithBaseURL:baseurl]; 
//Here, we tell the AFHTTPClient that the server is responding to us in JSON format. 
[client registerHTTPOperationClass:[AFJSONRequestOperation class]]; 

//Creating the dictionary containing the post parameters. 
NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:username, @"username", password, @"password", nil]; 


//AUTHENTIFICATION. Retrieving token and uid by POST method. 
[client postPath:@"/auth" parameters:params 
     success:^(AFHTTPRequestOperation *operation, id responseObject) 
{ 
    NSString *text = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding]; 
    NSLog(@"Response: %@", text); 
    [responseField setText:text]; 
    self.jsonResponse = responseObject; 

    //The NSJSONSerialization method to transform the NSData responseObject into a dictionnary does work 
    self.jsonResponse = [NSJSONSerialization JSONObjectWithData:responseObject options:0 error:nil]; 

    //This NSLog makes the app crash with an unrecognized selector sent error 
    NSLog(@"User ID: %@",[jsonResponse objectForKey:@"uid"]); 
} 
     failure:^(AFHTTPRequestOperation *operation, NSError *error) 
{ 
      NSLog(@"%@", [error localizedDescription]); 
      [responseField setText:[error localizedDescription]]; 
}]; 
+0

실제로'responseObject'의 클래스를 확인 했습니까? – Wain

+0

완전한 오류 메시지는 도움이 될 것입니다 ... –

+0

죄송합니다, 완전한 오류 메시지를 추가했습니다. responseObject의 클래스에 관해서는 isKindOfClass 메소드로 검사했고 실제로 NSData입니다. –

답변

6

당신은 application/jsonAccept 헤더를 설정하는 setDefaultHeader:value:에 대한 호출을 놓치고있어. 이것이 없다면, JSON 연산 클래스는 사용되지 않을 것인데, 이것은 으로 돌아가는 것을 의미하며, 이는 responseDataresponseObject으로 사용합니다.

+0

맞음! 헤더가 설정되고 모든 것이 매끄럽게 실행됩니다. Matt Thompson! 도서관 AFNetworking과 진행중인 Heroku 프로젝트에 대한 행운을 가져 주셔서 감사합니다. –

+2

이 방법으로 문제가 해결되면 대답을 수락하십시오! – fatuhoku

1

setDefaultHeader:value:으로 기본 머리글 수락을 application/json 값으로 설정하면 AFHTTPRequestOperation에 실제로 콜백에 참여하는 JSON이라고 알릴 수 있습니다.