Search code examples
iosios7afnetworking-2

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. *url start from "002_001" and end on "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];

Solution

  • You should create a serial queue, i'm using 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.