简体   繁体   English

在ios中按顺序下载音频文件

[英]download audio file in sequence in ios

I want to download seven mp3 clip files from server below code download one file at a time is there any better way to download all clip files in sequence. 我想从服务器下面的代码中下载七个mp3剪辑文件,一次下载一个文件,有没有更好的方法按顺序下载所有剪辑文件。 *url start from "002_001" and end on "002_007" * url从“ 002_001”开始,到“ 002_007”结束

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];

You should create a serial queue, i'm using GCD, dispatch_queue_t _queue = dispatch_queue_create("myQueue", DISPATCH_QUEUE_SERIAL); 您应该创建一个串行队列,我正在使用GCD, dispatch_queue_t _queue = dispatch_queue_create("myQueue", DISPATCH_QUEUE_SERIAL); and then use 然后使用

    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
}});

you create each task in serial queue and they will be executed in sequence. 您在串行队列中创建每个任务,它们将按顺序执行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM