With AFNetworking, how can I read the error message contained in request.responseString

NSLog(@"%@", request.responseString); 

This gives me the output {"errors":{"email":["is already taken"]}} .

I would like to save the email and the message line "is already taken" in the line displayed in the warning. How can I access these two elements in two lines?

+4
source share
4 answers

The response line is the raw output from the server. In this case, JSON is encoded. You can use one of the AFNetworking JSON classes (i.e. AFJSONRequestOperation ) to get the response back as a JSON object or to analyze it yourself using NSJSONSerialization . I would suggest using AFJSONRequestOperation .

+4
source
  NSData *data = [request.responseString dataUsingEncoding:NSUTF8StringEncoding]; id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil]; NSString *str = [[json objectForkey:@"errors"] objectForKey:@"email"][0]; 
+1
source

I used the following seems a little more reliable:

 [requestOperation setCompletionBlockWithSuccess:success failure:^(AFHTTPRequestOperation *operation, NSError *error) { id response = error.userInfo; if (response && [response isKindOfClass:[NSDictionary class]]) { NSDictionary *responseDictionary = (NSDictionary *)response; // AFNetworking hides the actual error response under this key if ([responseDictionary valueForKey:NSLocalizedRecoverySuggestionErrorKey]) { id suggestedRecovery = [responseDictionary valueForKey:NSLocalizedRecoverySuggestionErrorKey]; if ([suggestedRecovery isKindOfClass:[NSString class]]) { // Try to json decode string id json = [NSJSONSerialization JSONObjectWithData:[suggestedRecovery dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil]; if (json && [json isKindOfClass:[NSDictionary class]]) { responseDictionary = json; } } } // .. extract error message out of responseDictionary } }]; 
0
source
  NSData *responseData = [[error userInfo] objectForKey:@"data"]; if ([responseData length] > 0) { NSString *str = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding]; NSLog(@"%@", str); } 
-one
source

Source: https://habr.com/ru/post/1492262/


All Articles