2016-12-19 3 views
0

백그라운드 스레드에서 수행해야하는 여러 URL의 데이터를 동시에 다운로드해야 프런트 엔드 작업에 영향을 미치지 않습니다. NSOpeartionQueue 및 NSURLSession을 사용하려고합니다. 지금은 아래 코드를 사용하고 있습니다.NSOperationQueue를 동 기적으로 사용하여 백그라운드 스레드의 여러 URL에서 데이터 다운로드

for (int i=0;i<[tempArray count];i++) { 
      CheckList * checklist = (CheckList *)[tempArray objectAtIndex:i]; 

     [operationQueue addOperationWithBlock:^{ 

      dispatch_semaphore_t semaphore = dispatch_semaphore_create(0); 

      NSString * urlStr = [[BASE_URL stringByAppendingString:DOWNLOAD_CHECKLIST_METADATA_SUBURL] stringByAppendingFormat:@"%@/%d/%@",userName,[checklist.checklistId intValue],checklist.language]; 
      NSURL * url = [NSURL URLWithString:urlStr]; 
      NSLog(@"url is %@",url); 

      NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration]; 
      NSURLSession *session = [NSURLSession sessionWithConfiguration:config]; 

      NSMutableURLRequest * request = [[NSMutableURLRequest alloc] initWithURL:url]; 
      [request setTimeoutInterval:240.0]; 
      [request setValue:@"Application/JSON" forHTTPHeaderField:@"Content-Type"]; 
      NSURLSessionDataTask * downloadTask =[session dataTaskWithRequest:request completionHandler:^(NSData * data, NSURLResponse * response, NSError * error) 
                { 

                 NSString * str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; 
                 NSLog(@"response is %@",str); 
                }]; 
      [downloadTask resume]; 
      [indexSetBg addIndex:[checklist.checklistId intValue]]; 
      // but have the thread wait until the task is done 

      dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER); 


     }]; 

     } 

나는 기적으로 요청을 보낼 경우에, 첫번째 반응을 얻고 후 that.Means 수있는 방법이있다가, 두 번째 요청이 전송 될 필요가있다. 누구든지이 일을 수행하도록 나를 도울 수 있습니까?

대단히 감사합니다.

+0

실제 문제가 무엇의 끝에서

? 이전에 끝나기 전에 모든 다운로드가 완료되었거나 다운로드를 시작하지 않으려는 것을 계속하고 싶습니까? – shallowThought

답변

0

dispatch_semaphore_signal (세마포어)을 추가해야합니다. 당신의 NSURLSessionTask 완료 핸들러

for (int i=0;i<[tempArray count];i++) { 
     CheckList * checklist = (CheckList *)[tempArray objectAtIndex:i]; 

    [operationQueue addOperationWithBlock:^{ 

     dispatch_semaphore_t semaphore = dispatch_semaphore_create(0); 

     NSString * urlStr = [[BASE_URL stringByAppendingString:DOWNLOAD_CHECKLIST_METADATA_SUBURL] stringByAppendingFormat:@"%@/%d/%@",userName,[checklist.checklistId intValue],checklist.language]; 
     NSURL * url = [NSURL URLWithString:urlStr]; 
     NSLog(@"url is %@",url); 

     NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration]; 
     NSURLSession *session = [NSURLSession sessionWithConfiguration:config]; 

     NSMutableURLRequest * request = [[NSMutableURLRequest alloc] initWithURL:url]; 
     [request setTimeoutInterval:240.0]; 
     [request setValue:@"Application/JSON" forHTTPHeaderField:@"Content-Type"]; 
     NSURLSessionDataTask * downloadTask =[session dataTaskWithRequest:request completionHandler:^(NSData * data, NSURLResponse * response, NSError * error) 
               { 

                NSString * str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; 
                NSLog(@"response is %@",str); 
                dispatch_semaphore_signal(semaphore); 
               }]; 
     [downloadTask resume]; 
     [indexSetBg addIndex:[checklist.checklistId intValue]]; 
     // but have the thread wait until the task is done 

     dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER); 


    }]; 

    } 
+0

여기 내 문제는 하나씩 다운로드가 진행 중입니다. 그러나 모든 요청은 거의 함께 전송됩니다. 따라서 2 ~ 2 초 안에 모든 요청이 전송됩니다. 따라서 다운로드 버튼을 클릭 할 때마다 해당 URL에 대한 요청이 전송되었을 수 있습니다. – iOSManiac

+0

버튼 클릭 이벤트에서 각 데이터 작업에 대해 getTasksWithCompletionHandler를 사용하여 NSURLSession의 작업을 확인할 수 있습니다. url을 확인하고 버튼 클릭시 발생해야하는 작업 URL에 적합한 지 확인합니다. 그렇다면 아무 것도하지 않습니다. 당신이 만든 작업으로 다운로드 할 수 없다면 이벤트를 클릭하고 작업을 비활성화하십시오. 이를 위해 URL 사전 (키)과 조작 값을 보유해야만 중복 다운로드를 방지하기 위해 작업을 비활성화 할 수 있습니다 –

+0

여기 getTaskWithCompletionHandler의 예 (https : //gist.github.com/)를 참조하십시오. sudoepjaiswal/4ed79ac947e4776d4aed –