【问题标题】:why the data object of datataskwithurl is receiveing null?为什么 datataskwithurl 的数据对象正在接收 null?
【发布时间】:2015-07-10 21:20:54
【问题描述】:

我想从我的后端获取一些数据到我的应用程序。我写了以下代码:

NSURL *url = [NSURL URLWithString:@"http://domain.com/books"];
    config = [NSURLSessionConfiguration defaultSessionConfiguration];
    //curl -H 'Authorization: Token token="replace-with-token"'
    [config setHTTPAdditionalHeaders:@{@"Authorization":@"Token token=\"7601ea35c7eaf067fefe\""}];
    NSURLSession *session = [NSURLSession sessionWithConfiguration:config];
    [[session dataTaskWithURL:url completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        NSError *error1=nil;
        NSArray *JSON=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error1];
    }

      ] resume];

我检查了响应对象,我得到了 200,似乎获取请求进展顺利。但对于请求的数据,我得到了空值。我认为解析数据出错了。这是我期望收到的示例。我也将示例放入 JSON 查看器http://jsonviewer.stack.hu。它在第一面显示类似于 {} 的东西,但是当我打开它时,它会正确显示数据。

[
     {
        "id": 437,
        "name": "alchemist",
        "description": "story book.",
        "favorite": false,
        "difficulty": 3,
        "created_at": "2014-09-29T10:43:00.072Z",
        "updated_at": "2014-11-26T11:53:58.451Z",
        "photo": {
          "url": "https://amazon-/uploads/books/photo/437/alchemist.jpg",
          "thumbnail_url": "https://amazon-books.amazonaws.com/uploads/recipe/photo/437/alchemist-PC.jpg"
        }
      }
    ]

有人知道原因吗? 这是我的问题的更新,这里是 nsurlresponse 对象:

{ status code: 200, headers {
    "Cache-Control" = "max-age=0, private, must-revalidate";
    Connection = "keep-alive";
    "Content-Length" = 2;
    "Content-Type" = "application/json; charset=utf-8";
    Date = "Sat, 11 Jul 2015 15:26:58 GMT";
    Etag = "\"d751713988987e9331980363e24189ce\"";
    Server = "WEBrick/1.3.1 (Ruby/2.0.0/2015-04-13)";
    Via = "1.1 vegur";
    "X-Content-Type-Options" = nosniff;
    "X-Frame-Options" = SAMEORIGIN;
    "X-Request-Id" = "8e1abb2e-2526-4d10-99e7-d553b51457fd";
    "X-Runtime" = "0.125302";
    "X-Ua-Compatible" = "chrome=1";
    "X-Xss-Protection" = "1; mode=block";
} }

【问题讨论】:

    标签: ios json nsurlsession nsjsonserialization jsonresponse


    【解决方案1】:

    您收到的响应不是 JSON 格式。您可以使用以下代码进行检查:

    NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    NSLog("%@", string);
    

    【讨论】:

    • 我也试过这个。我不断收到这个 [ ] 作为回应。
    • 您是否将上面的代码放在完成处理程序块中?我尝试了您的代码并收到了 HTML 页面,其中包含以下信息:“您请求的页面不再存在或暂时不可用。”
    • 是的,我做到了。感谢您检查我的代码,这是我的代码和我的响应的示例。这是我在代码中使用的正确网址:“hyper-recipes.herokuapp.com/recipes
    • 是的,现在只有 [ ] 的响应。如我所见,您的代码没有任何问题,也许参数不正确。您可以在在线服务(例如 hurl.it)上检查您的请求,以查看该请求是否正常,然后再将其添加到您的代码中。
    • 感谢您提及在线服务,它看起来很有帮助。看来我的请求和它的参数很好。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-18
    相关资源
    最近更新 更多