2016-07-29 49 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的依賴,然後將當前操作分配給它,然後添加到操作隊列中。

這樣每個任務將在完成前一個任務後開始。希望這會幫助你。 :)