0

在繼續for循環之前,我想要使用AFJSONRequestOperation急切加載此代碼,但它以某種方式無法工作。下面的代碼在我的for循環中。即使請求尚未完成,如何阻止我的循環繼續進行?這將幫助我將所有從成功請求獲得的值按照我想要的順序放入數組中。在iPhone SDK上的For循環中使用AFJSONRequestOperation

這是代碼:

NSURL *url = [NSURL URLWithString:[nowShowingTitleListArray objectAtIndex:i]]; 
    NSURLRequest *theRequest = [NSURLRequest requestWithURL:url]; 
    [AFJSONRequestOperation addAcceptableContentTypes:[NSSet setWithObject:@"text/html"]]; 
    AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:theRequest 
    success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) 
    { 
     // Code when success 
    } 
    failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) 
    { 
     NSLog(@"Request Failed with Error: %@", [error localizedDescription]); 
    }]; 

    [operation start]; 

目前,我這樣做是爲了確保他們將獲取並添加到我的數組中的順序:

 NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:[nowShowingTitleListArray objectAtIndex:i]]]; 
     NSError *error; 
     NSDictionary *JSONDict = [NSJSONSerialization JSONObjectWithData:data 
                   options:kNilOptions 
                    error:&error]; 


     if (!JSONDict) 
     { 
      NSLog(@"Request Failed with Error: %@", [error localizedDescription]); 
     } 
     else 
     { 
      // Rest of code 
     } 

這也將有助於當網絡連接突然中斷時,我最大限度地減少了一些與請求有關的崩潰問題。任何幫助,將不勝感激。謝謝!

回答

0

爲什麼你是從同一個URL獲取數據兩次? 一旦使用AFJSONRequestOperation,然後dataWithContentsOfURL: 你是否在同一個for循環?

您已經有了JSON對象成功塊

success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) 
{ 
    // Code when success 
    // write success code here 
} 

你可以叫AFJSONRequestOperation環路多個網絡請求。

+0

不是。這些是不同的代碼。上面的那個是我想要的,但是隨着我的數組中的項目排列而變得紊亂,而下面的項目是有效的,但是速度較慢並且無法正確處理錯誤。 – jaytrixz 2013-03-24 09:54:03