2017-04-09 7 views
0

이미지 다운로드 목록과 이미지가 다운로드 될 때 진행률 표시 줄이 업데이트되는 iPad 앱이 있습니다. 진행률 표시 줄과 이미지 다운로드가 일치하지 않는 것 같습니다. 진행률 표시 줄은 이미지 다운로드가 완료되기 전에 항상 완료됩니다. 이미지를 다운로드 할 때마다 진행률 표시 줄을 증가시켜야하는 UpdateProgressBar 메서드가 있습니다.진행률 표시 줄이 이미지 다운로드와 동기화되지 않음

-(void)DownloadPhoto{ 
    NSMutableArray *failedDownloads = [[NSMutableArray alloc]init]; 
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{ 
     listPhoto = [CoreDataRead GetPhotoList:[self selectedAccountGuid]]; 
     dispatch_group_t downloadGroup = dispatch_group_create(); 
     for (Photo *item in listPhoto) { 
      NSString *imageName = item.photoName; 
      NSString *myURL = [NSString stringWithFormat:@"%@%@", @"http://acimagedownload.com/photos/", imageName]; 
      NSURL  *url  = [NSURL URLWithString:myURL]; 
      NSURLRequest *request = [NSURLRequest requestWithURL:url]; 

      dispatch_group_enter(downloadGroup); 
      [NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) { 

      if (connectionError == nil && data != nil) 
      { 
       if (data != nil) 
       { 
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
        NSString *documentsDirectory = [paths objectAtIndex:0]; 
        NSString* path = [documentsDirectory stringByAppendingPathComponent: [NSString stringWithFormat:@"%@%@",item.guid, @".png"]]; 

         [data writeToFile:path atomically:YES]; 
         NSLog(@"Photo Downloaded %@!", @""); 
        } 
        else 
        { 
         NSLog(@"image is not downloaded"); 
        } 
       } 
       else if (connectionError != nil) 
       { 
        [failedDownloads addObject:myURL]; 
        NSLog(@"Error %@",[connectionError description]); 
       } 
       else 
       { 
        [failedDownloads addObject:myURL]; 
        NSLog(@"Image Download Failed %@!", @""); 
       } 
       dispatch_group_leave(downloadGroup); 
       dispatch_async(dispatch_get_main_queue(), ^{ 
        [self UpdateProgressBar]; 
       }); 
      }]; 
      dispatch_group_wait(downloadGroup, DISPATCH_TIME_FOREVER); 
     } 
     dispatch_async(dispatch_get_main_queue(), ^{ 
      [self DownloadVideo]; 
     }); 
    }); 
} 

-(void)UpdateProgressBar{ 
    currentTask = currentTask + 1; 
    NSLog(@"Current Task %@!", [@(currentTask) stringValue]); 
    float progressPercentage = (float)currentTask/(float)taskCount; 
    [self.progressBar setProgress:progressPercentage animated:YES]; 
    if(currentTask == taskCount){ 
     [self ShowDoneAlert]; 
    } 
} 
+0

NSURLConnection'sendAsynchronousRequest'는 iOS 9에서 더 이상 사용되지 않습니다. 사실 NSURLConnection의 거의 모든 부분은 더 이상 사용되지 않습니다. 이전에 2 개의 주요 OS 버전에서 사용되지 않는 API를 사용하여 새로운 개발을하는 것은 현명한 방법이 아닙니다. NSURLSession을 사용하여 코드를 다시 작성하는 것이 좋습니다. –

+0

UpdateProgressBar의 코드는이 질문의 적절한 부분처럼 보입니다. – danh

+0

UpdateProgressBar 코드를 추가했습니다. –

답변

0

그것은 당신이 그 동작을 얻을 수 있지만, 내가 발견 한 것은 당신의 dispatch_group_wait(downloadGroup, DISPATCH_TIME_FOREVER);이 루프 내부에 있다는 것입니다 왜 updateProgressBar 방법을 보지 않고 말할 어렵다.

그래서 루프의 첫 번째 반복을 실행하면 스레드 실행이 중지되고 첫 번째 dispatch_group_leave을 기다립니다. 그 후 다음 반복이 계속됩니다.

이것이 바람직한 동작이라면 (실제로는 의심 스럽지만 실제로 다운로드를 병렬로 실행하고 싶다고 생각하는 경우) dispatch_semaphore_t 또는 직렬 대기열을 사용해야합니다.

+0

나는 그들에게 하나씩 달리기를 원한다. 나는 그것들을 평행하게 달리고 문제가 있었다. –

+0

문제점을 발견했습니다. 개수가 잘못되었습니다. 수를 정정하면 제대로 작동하기 시작합니다. –

+0

다운로드 전략에 대한 조언이 있으십니까? 나는 0에서 150 이미지 다운로드 사이에 가질 수 있습니다. 두 번? 같은 시간에 이미지를 다운로드하는 150 개의 스레드를 갖는 것이 좋은 생각이 아닐 것이라고 생각합니다. –