使用进度条下载多个(并行)文件(.mp4)并将其保存到库中

时间:2014-11-08 07:08:14

标签: ios objective-c grand-central-dispatch nsoperationqueue

我必须下载多个.mp4视频,并为每个视频显示progressBar。我必须在tableView中显示这些进度。我知道如何下载单个视频,并知道如何使用...

将其保存到图库

目前正在使用此代码..

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  NSLog(@"Downloading Started");

  NSString *urlToDownload = @"http://original.mp4";

  NSURL *url = [NSURL URLWithString:urlToDownload];

 NSData *urlData = [NSData dataWithContentsOfURL:url];

 if ( urlData )
 {

   NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
   NSString *documentsDirectory = [paths objectAtIndex:0];

   NSString *filePath = [NSString stringWithFormat:@"%@/%@", documentsDirectory,@"thefile.mp4"];

//saving is done on main thread
    dispatch_async(dispatch_get_main_queue(), ^{

           [urlData writeToFile:filePath atomically:YES];

          NSLog(@"File Saved !");
});
}

});

第一种方法

  1. 首先,如何使用上面的内容下载时显示进度 代码。
  2. 然后我也不知道它在哪里下载。我想知道 以上代码保存.mp4视频的路径,也想修改(保存 它在画廊)。
  3. 我还想显示每个视频的下载进度。
  4. 第二种方法

    我认为我必须使用NSOperationQueue异步运行下载,允许一定数量的并行执行等。但是不知道如何通过进步来实现它。

1 个答案:

答案 0 :(得分:0)

我创建了一些必须下载多个任务的东西,它也显示了每个任务的进度:http://github.com/ManavGabhawala/CAEN-Lecture-Scraper(这是针对mac的) 基本上你需要做的是创建一个自定义UITableViewCell类,其中包含进度条和一个IBOutlet到栏。然后让单元格的类符合NSURLSessionDownloadDelegate以获得进展。此外,我使用信号量来确保同时只发生3次下载。这是为了您方便的课程:

let downloadsAllowed = dispatch_semaphore_create(3)
class ProgressCellView: UITableViewCell
{
    @IBOutlet var progressBar: UIProgressView!
    @IBOutlet var statusLabel: UILabel!
    var downloadURL : NSURL!
    var saveToPath: NSURL!

    func setup(downloadURL: NSURL, saveToPath: NSURL)
    {
        self.downloadURL = downloadURL
        self.saveToPath = saveToPath
        statusLabel.text = "Waiting To Queue"
        // Optionally call begin download here if you don't want to wait after queueing all the cells.
    }

    func beginDownload()
    {
        statusLabel.text = "Queued"
        let session =
        NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration(), delegate: self, delegateQueue: NSOperationQueue())
        let task = session.downloadTaskWithURL(downloadURL)!
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {
            dispatch_semaphore_wait(downloadsAllowed, DISPATCH_TIME_FOREVER)
            dispatch_async(dispatch_get_main_queue(), {
                self.statusLabel.text = "Downloading"
            })
            task.resume()
        })
    }
}
extension ProgressCellView : NSURLSessionDownloadDelegate
{
    func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64)
    {
        progressBar.setProgress(Float(totalBytesWritten) / Float(totalBytesExpectedToWrite), animated: true)
    }
    func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didFinishDownloadingToURL location: NSURL)
    {
        // TODO: Write file downloaded.
        // Copy file from `location` to `saveToPath` and handle errors as necessary.
        dispatch_semaphore_signal(downloadsAllowed)
        dispatch_async(dispatch_get_main_queue(), {
            self.statusLabel.text = "Downloaded"
        })
    }
    func URLSession(session: NSURLSession, didBecomeInvalidWithError error: NSError?)
    {
        print(error!.localizedDescription)
        // TODO: Do error handling.
    }
}

将信号量值的创建更改为您希望的值(允许的并发下载数)。另请注意,必须在实例化后使用downloadURL和saveToPath在单元格上调用setup。如果您想立即排队并下载视频,请致电beginDownload()内的setup()。否则,只要您想开始下载所有视频,就可以在每个单元格上调用它。