2016-04-27 50 views
0

我有一個發送請求的嵌套循環。NSURLConnection在完成所有處理後發送請求

-(void) download 
{ 
    for(NSString *id in array) 
    { 
    //init with request and start the connection 
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy: NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0]; 
    NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request deletegate:self]; 
    [conn start]; 
    } 
} 

-(void) connection:(NSURLConnection *) connection didReceiveData:(NSData *) data 
{ 
//enter here secondly 
} 
-(void) connectionDidFinishLoading:(NSURLConnection *) connection 
{ 
//enter here last, after finish the for loop 
//my intention is use the downloaded data to do something before sending a new request. 
} 

的問題是,我想進入"-(void) connectionDidFinishLoading:(NSURLConnection *) connection"先在再次發送請求循環之前。

但目前它會完成for循環併發送所有請求,然後輸入到"-(void) connectionDidFinishLoading:(NSURLConnection *) connection"

+1

[NSURLConnection sendSynchronousRequest:request returningResponse:Response error:nil] –

+0

您可以使用帶有addDependency或MaxConcurrentOperation的NSOperationQueue。 –

+0

@PKT我認爲你的解決方案對我來說已經足夠了。謝謝 – user1151874

回答

1

你應該嘗試這NSURLConnection的在iOS9

棄用
for (NSString *URL in URLArray) { 
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL]; 

NSURLSessionTask *task = [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { 
    // check error and/or handle response here 
}]; 
[task resume]; 
} 

,並使用dispatch_group_t group = dispatch_group_create();

添加行for循環dispatch_group_enter(group);將調用

dispatch_group_notify(group, dispatch_get_main_queue(), ^{ 
    // Request Finish 
}); 

爲你的目標

0

在你的情況下,你需要嘗試阻止功能,因爲根據你的要求,你需要響應第一個連接的另一個請求。

for(NSString* url in array) 
{ 
    // Generate a NSURLRequest object from the address of the API. 
    NSURL *url = [NSURL URLWithString:urlLink]; 
    NSURLRequest *request = [NSURLRequest requestWithURL:url]; 

    // Send the request asynchronous request using block! 
    [NSURLConnection sendAsynchronousRequest:request 
             queue:[NSOperationQueue mainQueue] 
          completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) { 

          if (error) { 
           NSLog(@"Error in updateInfoFromServer: %@ %@", error, [error localizedDescription]); 
          } else if (!response) { 
           NSLog(@"Could not reach server!"); 
          } else if (!data) { 
           NSLog(@"Server did not return any data!"); 
          } else { 
           [self doStuffWithData:data]; 
          } 
         }]; 
} 
0

URL負載不是同步操作(或至少不應該是同步完成的),因爲它可能需要長達90秒的只是一個DNS查找失敗,而且幾乎無限長,如果服務器保持運球出數據。如果你阻止主線程的時間甚至只有這個時間的一小部分,iOS會殺死你的應用程序。

而不是在循環中調度請求並等待它們完成,您需要安排第一個請求(並且只有第一個請求)。然後,在您的connectionDidFinishLoading:方法(也可能是您的connection:DidFailWithError:方法)中,安排下一個請求。這樣說,除非你仍然需要支持iOS 6/10.8和更早的版本,否則你應該使用NSURLSession。 (相同的一般建議適用;代理方法名稱被改變以保護有罪)。

相關問題