2014-09-10 99 views
5

我想下載使用NSUrlSession文件的列表。的iOS 7 NSURLSession下載多個文件在後臺

我有一個計算成功下載@property (nonatomic) int downloadsSuccessfulCounter;的變量。當正在下載的文件,我禁用Download Button。當計數器等於下載列表大小,我再次啓用按鈕和計數器設置爲0。我的方法做到這一點:

-(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location { 

... 

    [[NSOperationQueue mainQueue] addOperationWithBlock:^ { 

     downloadsSuccessfulCounter++; 

     if(downloadsSuccessfulCounter == self.downloadList.count) { 
      NSLog(@"All downloads finished"); 

      [self.syncButton setEnabled:YES]; 

      downloadsSuccessfulCounter = 0; 
     } 
    }]; 

}

一切工作正常,但是當我再次打開ViewController我收到消息A background URLSession with identifier com.myApp already exists!。計數器未設置爲0,UI元素(UIButtons,UILabels)沒有響應。

我想這個問題是因爲NSURLSession仍然是開放的,但我真的不知道它是如何工作的。

我試過所有的教程,但其中99%僅用於下載1個文件,不超過1個... 任何想法?

這裏是我的代碼:

...  
@property (nonatomic, strong) NSURLSession *session; 
... 

    - (void)viewDidLoad { 
     [super viewDidLoad]; 

     appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate]; 

     self.downloadList = [[NSMutableArray alloc] init]; 

     NSURLSessionConfiguration *sessionConfiguration = [NSURLSessionConfiguration backgroundSessionConfiguration:@"com.myApp"]; 
     sessionConfiguration.HTTPMaximumConnectionsPerHost = 5; 
     self.session = [NSURLSession sessionWithConfiguration:sessionConfiguration delegate:self delegateQueue:nil]; 
} 

當我按下Download Button我調用這個方法( 我有一個Downloadable對象,它包含一個NSURLSessionDownloadTask):

-(void)startDownload { 

    for (int i=0; i<[self.downloadList count]; i++) { 
     Downloadable *d = [self.downloadList objectAtIndex:i]; 

     if (!d.isDownloading) { 
      if (d.taskIdentifier == -1) { 
       d.downloadTask = [self.session downloadTaskWithURL:[NSURL URLWithString:d.downloadSource]]; 

      }else { 
       d.downloadTask = [self.session downloadTaskWithResumeData:fdi.taskResumeData]; 
      } 

      d.taskIdentifier = d.downloadTask.taskIdentifier; 
      [d.downloadTask resume]; 
      d.isDownloading = YES; 
     } 
    } 
} 

當應用程序是背景:

-(void)URLSessionDidFinishEventsForBackgroundURLSession:(NSURLSession *)session{ 
    AppDelegate *appDelegate = [UIApplication sharedApplication].delegate; 

    [self.session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) { 

     if ([downloadTasks count] == 0) { 
      if (appDelegate.backgroundTransferCompletionHandler != nil) { 

       void(^completionHandler)() = appDelegate.backgroundTransferCompletionHandler; 

       appDelegate.backgroundTransferCompletionHandler = nil; 

       [[NSOperationQueue mainQueue] addOperationWithBlock:^{    
        completionHandler(); 

        UILocalNotification *localNotification = [[UILocalNotification alloc] init]; 
        localNotification.alertBody = @"All files downloaded"; 
        [[UIApplication sharedApplication] presentLocalNotificationNow:localNotification]; 

       }]; 
      } 
     } 
    }]; 
} 
+0

我目前也在探索這個......問題是會話標識符 - 它們必須對每個後續任務都是唯一的。根據此文本<<注意:您必須爲每個標識符創建一個會話(在創建配置對象時指定)。共享相同標識符的多個會話的行爲未定義。 >>本頁來自:https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/URLLoadingSystem/Articles/UsingNSURLSession.html – 2014-10-19 21:24:55

+0

我猜有兩個選擇我可以看到:1)編譯所有內容到一個zip文件,下載單個文件,然後將其解壓到客戶端(電話)一側 - 或者2)創建一個NSMutableArray任務,在運行時爲每個文件添加一個新的後臺會話並帶有唯一標識符。 – 2014-10-19 21:26:27

+0

本教程似乎有多個文件的前提:http://code.tutsplus.com/tutorials/working-with-nsurlsession-part-3--mobile-21879 – 2014-10-19 21:33:43

回答

3

所以,正如我在評論中提到的問題是,每個文件都需要一個獨特的NSURLSession,每個NSURLSession需要有一個唯一標識符的NSURLSessionConfiguration。

我認爲你很接近 - 並且在某些方面可能比我更合適...... 你只需要創建一個結構來將唯一ID傳遞到獨特的配置中,以填充唯一的會話(比如快10倍)。

這裏就是我所做的:

/* *檢索的文件列表下載 *也使用該列表的大小來實例化項目 *在我的情況,我打開一個字符返回文本文件我要下載的文件的名稱 */

- (void) getMediaList { 

    NSString *list = @"http://myserver/media_list.txt"; 
    NSURLSession *session = [NSURLSession sharedSession]; // <-- BASIC session 
    [[session dataTaskWithURL:[NSURL URLWithString:list] 
      completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { 

       NSString *stringFromData = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding]; 

       // Populate Arrays 
       REMOTE_MEDIA_FILE_PATHS = [stringFromData componentsSeparatedByString:@"\n"]; 
       [self instantiateURLSessions:[REMOTE_MEDIA_FILE_PATHS count]]; 


       // Start First File 
       [self getFile:[REMOTE_MEDIA_FILE_PATHS objectAtIndex:downloadCounter]:downloadCounter]; // this variable is 0 at the start 
      }] 
    resume]; 
} 

/* * 此設置配置的陣列和會話到適當大小, *它還提供了一個唯一的ID,以每一個 */

- (void) instantiateURLSessions : (int) size { 

    NSMutableArray *configurations = [NSMutableArray array]; 
    NSMutableArray *sessions = [NSMutableArray array]; 

    for (int i = 0; i < size; i++) { 
     NSString *index = [NSString stringWithFormat:@"%i", i]; 
     NSString *UniqueIdentifier = @"MyAppBackgroundSessionIdentifier_"; 
     UniqueIdentifier = [UniqueIdentifier stringByAppendingString:index]; 

     [configurations addObject: [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:UniqueIdentifier]]; 
     [sessions addObject:[NSURLSession sessionWithConfiguration: [configurations objectAtIndex:i] delegate: self delegateQueue: [NSOperationQueue mainQueue]]]; 
    } 

    NSURL_BACKGROUND_CONFIGURATIONS = [NSArray arrayWithArray:configurations]; 
    NSURL_BACKGROUND_SESSIONS = [NSArray arrayWithArray:sessions]; 
} 

/* *此設置每個文件的下載任務,以關閉陣列 的指數*它還地連接了路徑的實際文件 */

- (void) getFile : (NSString*) file :(int) index { 
    NSString *fullPathToFile = REMOTE_MEDIA_PATH; // Path To Server With Files 
    fullPathToFile = [fullPathToFile stringByAppendingString:file]; 

    NSURL *url = [NSURL URLWithString:fullPathToFile]; 
    NSURLSessionDownloadTask *downloadTask = [[NSURL_BACKGROUND_SESSIONS objectAtIndex:index ] downloadTaskWithURL: url]; 
    [downloadTask resume]; 

} 

/* *最後,在我的委託方法中,在下載完成後(從臨時數據中移出文件之後),檢查我是否完成,是否再次使用更新的計數器調用getFiles方法索引 */

-(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location 
{ 

    // Get the documents directory URL 
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
    NSString *documentsDirectory = [paths objectAtIndex:0]; 
    NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:LOCAL_MEDIA_PATH]; 
    NSURL *customDirectory = [NSURL fileURLWithPath:dataPath]; 

    // Get the file name and create a destination URL 
    NSString *sendingFileName = [downloadTask.originalRequest.URL lastPathComponent]; 
    NSURL *destinationUrl = [customDirectory URLByAppendingPathComponent:sendingFileName]; 

    // Move the file 
    NSError *error = nil; 
    NSFileManager *fileManager = [NSFileManager defaultManager]; 
    if ([fileManager moveItemAtURL:location toURL:destinationUrl error: &error]) { 

     // List 
     [self listCustomDirectory]; 

     if(downloadCounter < [REMOTE_MEDIA_FILE_PATHS count] -1) { 
      // Increment Counter 
      downloadCounter++; 

      // Start Next File 
      [self getFile:[REMOTE_MEDIA_FILE_PATHS objectAtIndex:downloadCounter]:downloadCounter]; 
     } 
     else { 
      // FINISH YOUR OPERATION/NOTIFY USER/ETC 
     } 
    } 
    else { 
     NSLog(@"Damn. Error %@", error); 
     // Do Something Intelligent Here 
    } 
}