NSLog(@"%@", request.responseString);
这给了我的输出{"errors":{"email":["is already taken"]}}
。
我想将电子邮件和消息字符串保存"is already taken"
为字符串以显示在警报中。如何将这两个项目访问到两个字符串中?
NSLog(@"%@", request.responseString);
这给了我的输出{"errors":{"email":["is already taken"]}}
。
我想将电子邮件和消息字符串保存"is already taken"
为字符串以显示在警报中。如何将这两个项目访问到两个字符串中?
响应字符串是服务器的原始输出。在这种情况下,它是 JSON 编码的。您可以使用 AFNetworking JSON 特定类之一(即AFJSONRequestOperation
)将响应作为 JSON 对象返回,或者使用NSJSONSerialization
. 我建议使用AFJSONRequestOperation
.
NSData *data = [request.responseString dataUsingEncoding:NSUTF8StringEncoding];
id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSString *str = [[json objectForkey:@"errors"] objectForKey:@"email"][0];
我使用了以下,似乎更强大一点:
[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
}
}];
NSData *responseData = [[error userInfo] objectForKey:@"data"];
if ([responseData length] > 0)
{
NSString *str = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(@"%@", str);
}