2012-08-05 17 views
9

Estoy enviando el siguiente mensaje a una instancia de AFHTTPClient. Espero que el bloque de éxito reciba un objeto Foundation (un diccionario) pero el depurador me muestra que JSON es un objeto _NSCFData. This question on SO indica que necesito configurar el encabezado Aceptar en 'application/json'. Bueno, estoy haciendo eso, pero AFNetworking todavía no está decodificando el JSON en el cuerpo de respuesta. Si decodifico el json usando NSJSONSerialization obtengo un NSDictionary como espero. ¿Qué estoy haciendo mal?AFNetworking devuelve un objeto _NSCFData en lugar de JSON

[client setDefaultHeader:@"Accept" value:@"application/json"]; 
[client postPath:@"/app/open_connection/" 
    parameters:params 
    success:^(AFHTTPRequestOperation *operation, id JSON) { 
     NSLog(@"successful login! %@", [JSON valueForKeyPath:@"status"]); 
    } 
    failure:^(AFHTTPRequestOperation *operation, NSError *error) { 
     NSLog(@"error opening connection"); 
     NSAlert *alert = [NSAlert alertWithError:error]; 
     [alert runModal]; 
    } 
]; 

Nota: Estoy programando el servidor en Python usando Django. El tipo de contenido de la respuesta es 'application/json'

+3

Trate de añadir [registerHTTPOperationClass cliente: [clase AFJSONRequestOperation]]; –

Respuesta

3

Pruebe esto ... Creo que tal vez haya algún problema con la configuración de su cliente.

NSMutableURLRequest *request = [client requestWithMethod:@"POST" path:@"/app/open_connection/" parameters:params]; 

AFJSONRequestOperation *operation = 
[AFJSONRequestOperation JSONRequestOperationWithRequest:request 
    success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) { 
     NSLog(@"successful login! %@", [JSON valueForKeyPath:@"status"]); 
    } 
    failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) { 
     NSLog(@"error opening connection"); 
     NSAlert *alert = [NSAlert alertWithError:error]; 
     [alert runModal]; 
}]; 
[operation start]; 
+0

Eso funciona, por lo que debe ser un problema con la configuración de mi AFHTTPClient. –

+0

Para mí, el problema era que el contenido se devolvía como texto/html. Al principio, pensé que podría simplemente modificar los tipos de contenido aceptables para agregar texto/html, pero eso aún daba como resultado datos de NSCF porque aparentemente tiene que estar en el tipo de mime apropiado para permitir que el contenido se analice correctamente como JSON en lugar de un gran blob de texto. – user1214836

6

Cuando se trabaja con AFHTTPClient y una API JSON, normalmente necesitará establecer estos tres valores:

httpClient.parameterEncoding = AFJSONParameterEncoding; 
[httpClient setDefaultHeader:@"Accept" value:@"application/json"]; 
[httpClient registerHTTPOperationClass:[AFJSONRequestOperation class]]; 

Ahora, cuando se hace una solicitud utilizando su cliente, que sabrá para analizar la respuesta como JSON.

[httpClient postPath:@"/app/open_connection/" 
      parameters:params 
      success:^(AFHTTPRequestOperation *operation, id response) { 
       NSLog(@"JSON! %@", response); 
      } 
      failure:^(AFHTTPRequestOperation *operation, NSError *error) { 
      }]; 

Aquí hay un truco que descubrí también. En el objeto NSError puede analizar y recuperar el mensaje de error (si la respuesta HTTP tenía un mensaje de error JSON):

failure:^(AFHTTPRequestOperation *operation, NSError *error) { 
    NSDictionary *JSON = 
    [NSJSONSerialization JSONObjectWithData: [error.localizedRecoverySuggestion dataUsingEncoding:NSUTF8StringEncoding] 
            options: NSJSONReadingMutableContainers 
             error:nil]; 
      failureCallback(JSON[@"message"]); 
} 
+0

No se pudo averiguar por qué AFHTTPClient estaba devolviendo NSCFData - resulta que "application/json" no se configuró. Muchas gracias! – r00m

Cuestiones relacionadas