AFNetworking iOS - 在GET请求完成后查看NSLog中的实际数据的方法

时间:2015-10-22 10:26:16

标签: ios json ajax api afnetworking

我简单地调用了一个名为queryJobAndMoveWithName的api方法,该方法产生GET请求(例如http://www.imdb.com/xml/find?json=1&nr=1&nm=on&q=jennifer)。

然而,当我看看日志responseJSON获取呈现为< 57652068 6f706520 746f206c 61756e63 68205353 4c206163 63657373 20746f20 616c6c20 70616765 73206f6e 20494d44 6220696e 20746865 20766572 61722066 79206e65 75747572 652e0d0a 0d0a5468 616e6b73 20666f72 20796f75 72207061 7469656e 63652e>除了{XXX:XXX,XXX:XXX}

- (void)queryJobAndMoveWithName:(NSString *)name completionHandler:(void (^)(NSDictionary *resultsJSON, NSError *error))completionHandler {

    NSString *url = [NSString stringWithFormat:@"%@%@?json=1&nr=1&nm=on&q=%@", kAPIHost, kSearchPath, name];

    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/javascript" ,@"text/html", @"text/plain", @"text/json", nil];

    [manager GET:url parameters:nil success:^(AFHTTPRequestOperation *operation, id responseJSON) {
        NSLog(@"JSON: %@", responseJSON);
        completionHandler(responseJSON, nil);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Error: %@", error);
        completionHandler(nil, error);
    }];
}

这是一个从视图控制器调用api方法的方法

- (IBAction)searchButtonTapped:(id)sender {
    NSLog(@"%@",self.searchTextField.text);
    NSString *queryName = self.searchTextField.text;
    NSArray *fullName = [queryName componentsSeparatedByString:@" "];
    NSString *formattedFullName = [fullName componentsJoinedByString:@"+"];

    FPAImdbApi *imdbApi = [[FPAImdbApi alloc] init];
    [imdbApi queryJobAndMoveWithName:formattedFullName completionHandler:^(NSDictionary *resultsJSON, NSError *error) {
        if (error) {
            NSLog(@"error: %@", error);
        } else if (resultsJSON) {
            NSLog(@"result json: \n %@", resultsJSON);
        } else {
            NSLog(@"nothing found");
        }

    }];

}

所以我的问题是如何查看除内存形式以外的日志中生成的JSON的内容

1 个答案:

答案 0 :(得分:0)

您还没有告诉经理响应是JSON,在这里您将响应序列化器设置为HTTP:

manager.responseSerializer = [AFHTTPResponseSerializer serializer];

将它改为JSON:

manager.responseSerializer = [AFJSONResponseSerializer serializer];

在错误块中,您可以执行以下操作来打印来自服务器的响应:

if (error) {
    NSHTTPURLResponse *respone = error.userInfo[AFNetworkingOperationFailingURLResponseErrorKey];
    NSData *errorData = error.userInfo[AFNetworkingOperationFailingURLResponseDataErrorKey];
    NSString *responseString = [[NSString alloc] initWithData:errorData encoding:NSUTF8StringEncoding];
    NSLog(@"Response: %@", responseString);
}