[英]download audio file in sequence in ios
我想從服務器下面的代碼中下載七個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
}});
您在串行隊列中創建每個任務,它們將按順序執行。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.