为什么datataskwithurl的数据对象接收null?

时间:2015-07-10 21:20:55

标签: ios json nsurlsession nsjsonserialization jsonresponse

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

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,看起来抓取请求进展顺利。但是对于请求的数据我得到了null。我认为从解析数据出错了。这是我希望收到的一个例子。我把这个例子放到了JSON viewer 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";
} }

1 个答案:

答案 0 :(得分:0)

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

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