2016-07-29 70 views
0

我正在swift中下载文件,并且下载会话由每个表格视图单元格上的按钮触发。但是,我不希望下一次下载(如果有人按下另一个单元格上的下载按钮)发生,直到上一次完成。下载在Swift中完成后发送?

有没有办法让我可以使用像dispatch_after这样的东西来实现这一点?

这里是我的代码下载发生,如果它有帮助。

//FUNCTION TO DOWNLOAD THE PDF 
//PASS THE ONLINE PDF URL AS NSURL 
//ASYNC REQUEST 
let defaultSession = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration()) 
var dataTask: NSURLSessionDataTask? 
var temp_name = String() 
var temp_index = Int() 
var temp_indexPath = NSIndexPath() 

lazy var downloadsSession: NSURLSession = { 

    let configuration = NSURLSessionConfiguration.defaultSessionConfiguration() 
    let session = NSURLSession(configuration: configuration, delegate: self, delegateQueue: nil) 
    return session 
}() 
func getUrl(name: String) -> NSURL?{ 
    let documentsUrl = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first as NSURL! 
    return documentsUrl.URLByAppendingPathComponent(name) 
} 

func getIndex() -> Int?{ 
    return temp_index 
} 

func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didFinishDownloadingToURL location: NSURL) { 

    if let originalURL = downloadTask.originalRequest?.URL?.absoluteString, 
     destinationURL = getUrl(temp_name){ 

     let fileManager = NSFileManager.defaultManager() 
     do { 
      try fileManager.removeItemAtURL(destinationURL) 
     } catch { 
      // Non-fatal: file probably doesn't exist 
     } 
     do { 
      try fileManager.copyItemAtURL(location, toURL: destinationURL) 
     } catch let error as NSError { 
      print("Could not copy file to disk: \(error.localizedDescription)") 
     } 
    } 


    if let url = downloadTask.originalRequest?.URL?.absoluteString { 
     activeDownloads[url] = nil 

     if let trackIndex = getIndex() { 
      dispatch_async(dispatch_get_main_queue(), { 
       defaults.setBool(false, forKey: self.temp_name + "_downloading") 


       self.tableView.reloadRowsAtIndexPaths([NSIndexPath(forRow: trackIndex, inSection: 0)], withRowAnimation: .None) 
      }) 
     } 
    } 


} 


func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) { 

    if let downloadUrl = downloadTask.originalRequest?.URL?.absoluteString, 
     download = activeDownloads[downloadUrl] { 
     download.progress = Float(totalBytesWritten)/Float(totalBytesExpectedToWrite) 
     if let trackIndex = getIndex(), let cell = tableView.cellForRowAtIndexPath(NSIndexPath(forRow: trackIndex, inSection: 0)) as? MainTableViewCell { 
      dispatch_async(dispatch_get_main_queue(), { 
       cell.progress.progress = download.progress 
       if(download.progress < 1.0){ 
        cell.progress.hidden = false 
       } 
       else{ 
        cell.progress.hidden = true 
       } 
      }) 
     } 

    } 

} 

// Action triggered by UIButton (in this case the download button) 
//Access tag, which is the IndexPath.row, using sender.tag 
@IBAction func downloadFile(sender: UIButton){ 
    let indexPath = NSIndexPath(forRow: sender.tag, inSection: 0) 
    let cell = tableView.cellForRowAtIndexPath(indexPath) as! MainTableViewCell 
    cell.downloadButton.hidden = true 
    cell.progress.progress = 0 
    cell.progress.hidden = false 



    let isAvailable = true 
    let key = names[sender.tag] + "_offline" 
    defaults.setValue(isAvailable, forKey: key) 
    let name = (names[sender.tag]) 
    let fileName = name + ".pdf" 
    let attachment = attachments[sender.tag] 
    temp_name = fileName 
    temp_index = sender.tag 
    temp_indexPath = indexPath 
    let destinationURL = getUrl(temp_name)! 
    defaults.setValue(destinationURL.path!, forKey: name + "_path") 
    defaults.synchronize() 
    defaults.setBool(true, forKey: name + "_downloading") 
    let urlString = attachment 
    let url = NSURL(string: urlString) 

    let download = PDFDownload(url: urlString) 

    download.downloadTask = downloadsSession.downloadTaskWithURL(url!) 
    download.downloadTask!.resume() 
    download.isDownloading = true 

    activeDownloads[download.url] = download 

} 

有一个布尔值用于存储是否正在进行下载会话,所以也许有一种方法可以使用它?等到布尔值为false来执行我的代码?

+0

您可以在第一次点击按钮后禁用按钮,并在网络调用的完成处理程序中重新启用它 –

+0

让我澄清 - 它们是每个表格视图单元格上的按钮,我仍然希望其他一些工作,但只是等到开始下载 –

+0

啊,你可以做的一件事就是使用一个串行dispatch_queue,或者你可以把它包装在一个NSOperation中,并使用一个串行NSOperation队列 –

回答

2

@Deepak kumar答案是正确的,但为每个操作添加依赖不是好主意。 你可以用更简单的方法做到这一点。只需要3个步骤。

  1. 创建NSOperationQueue对象。
  2. 然后将属性maxConcurrentOpeations设置为1.
  3. 然后将操作添加到队列中,它将逐个执行操作。
+0

真棒 - 这使得更有意义 –

2

您可以使用NSOperationQueue来完成此操作。创建一个操作队列和一个NSOperation对象,以存储在当前操作之前添加到操作队列的先前操作。在每次点击tableviewcell的按钮时创建新的NSOperation实例,并在添加到operationqueue之前执行以下操作。

1-检查tempoperation是否为零。然后将当前操作分配给它,然后添加到操作队列中。 2. else首先添加对tempoperation的依赖,然后将当前操作分配给它,然后添加到操作队列中。

这样每个任务将在完成前一个任务后开始。希望这会帮助你。 :)