2014-08-31 69 views
1

我想从服务器下载7个mp3剪辑文件下载代码一次下载一个文件有没有更好的方法来按顺序下载所有剪贴文件。 *从 “002_001” URL开始和 “002_007” 结束在ios中按顺序下载音频文件

NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration]; 
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration]; 

NSString *url = @"http://www.xyzxx.com/002_001.mp3" 
NSURL *URL = [NSURL URLWithString:url]; 
NSURLRequest *request = [NSURLRequest requestWithURL:URL]; 

NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) { 
    NSURL *documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil]; 
    return [documentsDirectoryURL URLByAppendingPathComponent:[response suggestedFilename]]; 
} completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) { 
    NSLog(@"File downloaded to: %@", filePath); 

    //Save file in destination folder 
    NSString *stringPath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0]stringByAppendingPathComponent:@"/IMCFolder"]; 
    error = nil; 
    if (![[NSFileManager defaultManager] fileExistsAtPath:stringPath]) 
     [[NSFileManager defaultManager] createDirectoryAtPath:stringPath withIntermediateDirectories:NO attributes:nil error:&error]; 

    NSData *data = [NSData dataWithContentsOfURL:filePath]; 
    if(data) 
    { 
     stringPath = [stringPath stringByAppendingPathComponent:[URL lastPathComponent]]; 
     [data writeToFile:stringPath atomically:YES]; 
    } 


}]; 
[downloadTask resume]; 

回答

2

您应该创建一个串行队列,我使用GCD,dispatch_queue_t _queue = dispatch_queue_create("myQueue", DISPATCH_QUEUE_SERIAL);然后用

dispatch_sync(_queue, ^{ 
    NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) { 
     // some code 
    } completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) { 
    //some code 
}}); 

您在创建每个任务串行队列,它们将按顺序执行。