get progress from dataTaskWithURL in swift

后端 未结 6 1145
庸人自扰
庸人自扰 2020-11-30 03:49

Is there any way to get progress from dataTaskWithURL in swift while the data is downloading?

NSURLSession.sharedSession().dataTaskWithURL(...)         


        
6条回答
  •  爱一瞬间的悲伤
    2020-11-30 04:31

    in class declare

    class AudioPlayerViewController: UIViewController, URLSessionDelegate, URLSessionDataDelegate, URLSessionDownloadDelegate{
    
    
             var defaultSession: URLSession!
             var downloadTask: URLSessionDownloadTask!
    

    in download method

                defaultSession = Foundation.URLSession(configuration: .default, delegate: self, delegateQueue: nil)
                downloadProgress.setProgress(0.0, animated: false)
                downloadTask = defaultSession.downloadTask(with: audioUrl)
                downloadTask.Resume()
    

    And add following delegates:

    func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
    
        DispatchQueue.main.async {
            self.downloadProgressBar.setProgress(Float(totalBytesWritten)/Float(totalBytesExpectedToWrite), animated: true)
        }
    }
    
    func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
            DispatchQueue.main.async {
    
    //DOWNLOAD SUCCESSFUL AND FILE PATH WILL BE IN URL.
    
    }
    }
    

提交回复
热议问题