2012-09-10 81 views
6

它看起來像我沒有得到塊的概念,完全尚未...出NSURLResponse完成塊的獲取數據

在我的代碼,我要走出從asychronous block JSON數據返回到從'outer'方法。我搜索了一下,發現如果定義了一個variable with __block,那麼這個變量被擴展爲block

但由於某種原因返回的json對象爲零。我想知道爲什麼?

- (NSMutableDictionary *)executeRequestUrlString:(NSString *)urlString 
{ 
__block NSMutableDictionary *json = nil; 
NSURL *url = [NSURL URLWithString:urlString]; 
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; 

[request setHTTPShouldHandleCookies:YES]; 
[request setHTTPMethod:@"GET"]; 
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-type"]; 

NSString *cookieString = [self.userDefaults objectForKey:SAVED_COOKIE]; 

[request addValue:cookieString forHTTPHeaderField:@"Cookie"]; 

[NSURLConnection sendAsynchronousRequest:request 
            queue:[NSOperationQueue currentQueue] 
         completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) 
         { 

          NSLog(@"dataAsString %@", [NSString stringWithUTF8String:[data bytes]]); 

          NSError *error1; 
          NSMutableDictionary * innerJson = [NSJSONSerialization 
            JSONObjectWithData:data 
               options:kNilOptions 
               error:&error1]; 
          json = innerJson; 

         }]; 

    return json; 
} 

回答

18

首先,要回答你的問題:

但由於某些原因返回的JSON對象是nil。我想知道爲什麼?

您返回的變量尚未在您返回時設置。 sendAsynchronousRequest:queue:completionHandler:方法返回後,您無法立即收穫結果:呼叫必須在回撥您的區塊並設置json變量之前完成往返。

現在快速記下如何處理它:您的方法試圖將異步調用轉換爲同步調用。如果可以,儘量保持異步。而不是期望一個返回NSMutableDictionary*的方法,使把它自己的塊的方法,並把字典是塊當sendAsynchronousRequest:方法完成:將數據從服務器何時到來

- (void)executeRequestUrlString:(NSString *)urlString withBlock:(void (^)(NSDictionary *jsonData))block { 
    // Prepare for the call 
    ... 
    // Make the call 
    [NSURLConnection sendAsynchronousRequest:request 
            queue:[NSOperationQueue currentQueue] 
         completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) { 
     NSLog(@"dataAsString %@", [NSString stringWithUTF8String:[data bytes]]); 
     NSError *error1; 
     NSMutableDictionary * innerJson = [NSJSONSerialization 
      JSONObjectWithData:data options:kNilOptions error:&error1 
     ]; 
     block(innerJson); // Call back the block passed into your method 
     }]; 

} 
+1

這是一個絕對輝煌的答案恕我直言!我花了相當長的一段時間才明白它,但它是值得的。謝謝,我學到了很多! – brainray

2

當你調用sendAsynchronousRequest:queue:completionHandler:,您所要求的異步請求。所以它將請求和塊排隊並立即返回。在將來的某個時刻,會發出請求,並在此之後的某個點運行完成塊。但到那個時候,return json已經運行很久了。

如果您希望能夠同步返回數據,則必須發出同步請求。這將掛起這個線程直到它完成,所以它不能成爲主線程。

0

檢查字符串使用下面的代碼:

NSLog(@"dataAsString %@", [NSString stringWithUTF8String:[data bytes]]); 

如果字符串是在一個適當的JSON格式,只有你的JSON對象將是正確的。

希望能得到這個!