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

标签 ios ios7 afnetworking-2

我想从服务器下载七个 mp3 剪辑文件,代码如下,一次下载一个文件,有没有更好的方法可以按顺序下载所有剪辑文件。 *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];

最佳答案

你应该创建一个串行队列,我正在使用 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
}});

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

关于ios - 在ios中按顺序下载音频文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25594001/

相关文章:

iphone - 加载新 View 时播放视频

ios - 如何在滑动操作后更新 tableview 行?

ios - 如何在 ios7 中本地化家庭/名字顺序和间距

ios - 检测 iOS 7 中的静音开关问题

ios - 同一 Controller 中的两个 UITableView

ios - 在 iOS 的 AFNetworking2 中尝试示例应用程序但被取消错误

ios - iOS应用程序在Xcode控制台以外的地方记录日志

iphone - nsmutablearray 浮点对象返回零

ios - 如何使用 AFNetworking 发送 HTTP POST 请求?

objective-c - AFHTTPSessionManager 未解除分配