2015-07-10 171 views
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"; 
} } 

回答

0

您收到的反應是不是JSON格式。你可以用下面的代碼檢查它:

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

我試過這個了。我不斷收到這個[]作爲迴應。 – MKH

+0

您是否將代碼置於完成處理程序塊中?我嘗試了您的代碼並收到了HTML頁面,其中包含以下信息:「您請求的頁面不再存在或暫時不可用。」 –

+0

是的,我做到了。感謝您檢查我的代碼,這是我的代碼和我的迴應的一個例子。在這裏它是一個正確的網址,我在我的代碼中使用:「http://hyper-recipes.herokuapp.com/recipes」 – MKH

相關問題