swift iOS - NSURLSession无法正确下载多个文件

时间:2015-09-26 16:14:10

标签: ios swift download nsurlsession

我的应用程序同时下载多个文件。我的方案如下:

  1. 用户点击下载按钮。
  2. 初始化下载UITableViewCell,实现NSURLSessionDelegate以下载指定文件。
  3. 开始下载。下载单元格显示在使用NSURLSession提供的代理下载文件时的进度。
  4. 文件本地保存在文档文件夹中。
  5. 用户单击按钮可清除所有已完成的下载。此按钮清除阵列' downloadQueue' Download Cell使用。该按钮还调用tableView.reloadData来更新tableView
  6. 问题是,当用户启动多次下载时,不会出现问题。所有文件同时正确下载。但是,当用户单击步骤5中描述的按钮,然后尝试下载另一个文件时,下载进度会立即显示100%完成。并且没有文件在本地保存。这可能是因为立刻调用了didFinishDownloadingToURL。

    以下是我的DownloadCell.swift的完整代码

    class DownloadCell: UITableViewCell, NSURLSessionDelegate {
    
    
    @IBOutlet weak var lblSongName: UILabel!
    @IBOutlet weak var progressBar: UIProgressView!
    @IBOutlet weak var progressCount: UILabel!
    
    var song: Song!
    
    var task: NSURLSessionTask!
    
    var percentageWritten: Float = 0.0
    var taskTotalBytesWritten = 0
    var taskTotalBytesExpectedToWrite = 0
    
    lazy var session: NSURLSession = {
        let config = NSURLSessionConfiguration.ephemeralSessionConfiguration()
        config.allowsCellularAccess = false
        let session = NSURLSession(configuration: config, delegate: self, delegateQueue: NSOperationQueue.mainQueue())
        return session
        }()
    
    
    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    
        }
    
    func startDownload() {
    
        lblSongName.text = song.songName
    
        if self.task != nil {
            return
        }
        let url = NSURL(string: song.songDownloadLink)!
        let req = NSMutableURLRequest(URL: url)
        let task = self.session.downloadTaskWithRequest(req)
        self.task = task
        task.resume()
    
    }
    
    func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten writ: Int64, totalBytesExpectedToWrite exp: Int64) {
        taskTotalBytesWritten = Int(writ)
        taskTotalBytesExpectedToWrite = Int(exp)
        percentageWritten = Float(taskTotalBytesWritten) / Float(taskTotalBytesExpectedToWrite)
        progressBar.progress = percentageWritten
        progressCount.text = String(Int(percentageWritten*100)) + "%"
    
        print("(\(taskTotalBytesWritten) / \(taskTotalBytesExpectedToWrite))")
    }
    
    func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?) {
        if error != nil {
            print("Completed with error: \(error)")
        }
    }
    
    func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didFinishDownloadingToURL location: NSURL) {
    
        do {
        let documentsDirectoryURL =  NSFileManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first as NSURL!
        progressCount.text = "Done!"
        progressBar.progress = 100.0
    
        try NSFileManager().moveItemAtURL(location, toURL: documentsDirectoryURL.URLByAppendingPathComponent(song.songName + ".mp3"))
    
            //Handling Badge Values
            let tabBar = UIApplication.sharedApplication().keyWindow?.rootViewController as! UITabBarController
            let downloadVC = tabBar.viewControllers?[1] as! DownloadViewController
            let badgeValue = Int(downloadVC.tabBarItem.badgeValue!)! - 1
            downloadVC.tabBarItem.badgeValue = String(badgeValue)
    
            if badgeValue == 0 {
                downloadVC.tabBarItem.badgeValue = nil
            }
    
        } catch {
            print("Error occurred during saving.")
            progressCount.text = String(error)
    
        }
    
    }
    

    }

1 个答案:

答案 0 :(得分:0)

也许你应该实现uitableviewcell的prepareForReuse功能?如果重用这些单元格,它们仍然可能有任务,因此startDownload在开始时返回。此外,进度条的值不会重置为0.