0

我需要你的帮助。我在 MaShape 上为 Metascore 找到了一个 API,但我无法让它工作。我使用 Cocoapod 下载 Unirest 框架并从 Mashape 复制粘贴代码片段

NSDictionary* headers = @{@"X-Mashape-Authorization": @"wZrjWIiAsqdSLGIh3DQzrKoZ5Y3wlo6E"};
NSDictionary* parameters = @{@"title": @"The Elder Scrolls V: Skyrim", @"platform": 1, };

UNIHttpJsonResponse* response = [[UNIRest post:^(UNIBodyRequest* request) {
  [request setUrl:@"https://byroredux-metacritic.p.mashape.com/find/game"];

  [request setHeaders:headers];
  [request setParameters:parameters];
}] asJson];

它给了我一堆错误,我将其修复为:

NSDictionary* headers = @{@"X-Mashape-Authorization": @"wZrjWIiAsqdSLGIh3DQzrKoZ5Y3wlo6E"};
    NSDictionary* parameters = @{@"title": @"The Elder Scrolls V: Skyrim", @"platform": @"1", };

    UNIHTTPJsonResponse* response = [[UNIRest post:^(UNISimpleRequest* request) {
        [request setUrl:@"https://byroredux-metacritic.p.mashape.com/find/game"];

        [request setHeaders:headers];
        [request setParameters:parameters];
    }] asJson];

但是每当我去调试代码并查看响应时,它都是空的,就好像 api 没有工作一样。你们能告诉我我做错了什么吗?

谢谢

4

1 回答 1

3

您的(固定)代码片段看起来不错(第一个确实是错误的),您应该能够像这样打印结果:

UNIHTTPJsonResponse *response = [[UNIRest post:^(UNISimpleRequest *request) {
    [request setUrl:@"https://byroredux-metacritic.p.mashape.com/find/game"];

    [request setHeaders:headers];
    [request setParameters:parameters];
}] asJson];

NSDictionary *json = [NSJSONSerialization JSONObjectWithData:response.rawBody
                                                         options:kNilOptions
                                                           error:nil];
NSLog(@"Response status: %ld\n%@", (long) response.code, json);

但与其进行同步调用,我还建议您切换到异步方式,以及检查过程中是否有任何错误和 JSON 解析:

[[UNIRest post:^(UNISimpleRequest *request) {
    [request setUrl:@"https://byroredux-metacritic.p.mashape.com/find/game"];
    [request setHeaders:headers];
    [request setParameters:parameters];
}] asJsonAsync:^(UNIHTTPJsonResponse* response, NSError *error) {
    if (error) {
        // Do something with the error
    }

    NSError *jsonError;
    NSDictionary *json = [NSJSONSerialization JSONObjectWithData:response.rawBody
                                                         options:kNilOptions
                                                           error:&jsonError];
    if (jsonError) {
        // Do something with the error
    }

    NSLog(@"Async response status: %ld\n%@", (long) response.code, json);

    // Unirest also provides you this which prevents you from doing the parsing
    NSLog(@"%@", response.body.JSONObject);
}];
于 2014-06-06T22:55:58.270 回答