0
我想从我的后端获取一些数据到我的应用程序。我写了下面的代码:为什么datataskwithurl的数据对象正在接收空值?
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";
} }
我试过这个了。我不断收到这个[]作为回应。 – MKH
您是否将代码置于完成处理程序块中?我尝试了您的代码并收到了HTML页面,其中包含以下信息:“您请求的页面不再存在或暂时不可用。” –
是的,我做到了。感谢您检查我的代码,这是我的代码和我的回应的一个例子。在这里它是一个正确的网址,我在我的代码中使用:“http://hyper-recipes.herokuapp.com/recipes” – MKH