2012-08-05 11 views
9

Sto inviando il seguente messaggio a un'istanza di AFHTTPClient. Prevedo che al blocco di successo venga inviato un oggetto Foundation (un dizionario) ma il debugger mi mostra che JSON è un oggetto _NSCFData. This question on SO afferma che ho bisogno di impostare l'intestazione Accept su 'application/json'. Bene, lo sto facendo, ma AFNetworking non sta ancora decodificando il JSON nel corpo della risposta. Se decodifico personalmente il json usando NSJSONSerialization, ottengo un NSDictionary come mi aspetto. Che cosa sto facendo di sbagliato?AFNetworking restituisce un oggetto _NSCFData anziché 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: sto programmando il server in Python utilizzando Django. Il tipo di contenuto della risposta è 'application/json'

+3

Prova ad aggiungere [client registerHTTPOperationClass: [class AFJSONRequestOperation]]; –

risposta

3

Prova questo ... Penso che forse c'è qualcosa di sbagliato nelle impostazioni del tuo client.

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

Questo funziona, quindi deve essere un problema con la configurazione del mio AFHTTPClient. –

+0

Per me, il problema era che il contenuto veniva restituito come text/html. Inizialmente, pensavo di poter semplicemente modificare i acceptContentTypes per aggiungere text/html, ma questo ha comunque portato a dati NSCF perché apparentemente doveva essere nel tipo mime appropriato per consentire il corretto utilizzo del contenuto come JSON invece di un big blob di testo. – user1214836

6

Quando si lavora con AFHTTPClient e un API JSON, in genere necessario impostare tutte e tre queste impostazioni:

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

Ora, quando si effettuano le richieste il tuo programma, saprà per analizzare la risposta come JSON.

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

Ecco un trucco che ho scoperto anche io. Nell'oggetto NSError è possibile analizzarlo e recuperare il messaggio di errore (se la risposta HTTP aveva un messaggio di errore JSON):

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

Impossibile capire perché AFHTTPClient stava restituendo NSCFData - risulta che "application/json" non è stato impostato. Grazie mille! – r00m

Problemi correlati