Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get progress from dataTaskWithURL in swift

Tags:

ios

swift

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

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

I need to show progress bar while the data is downloading.

like image 444
taffarel Avatar asked May 30 '15 08:05

taffarel


2 Answers

You can simply observe progress property of the URLSessionDataTask object.

Example:

import UIKit  class SomeViewController: UIViewController {    private var observation: NSKeyValueObservation?    deinit {     observation?.invalidate()   }    override func viewDidLoad() {     super.viewDidLoad()      let url = URL(string: "https://source.unsplash.com/random/4000x4000")!     let task = URLSession.shared.dataTask(with: url)      observation = task.progress.observe(\.fractionCompleted) { progress, _ in       print("progress: ", progress.fractionCompleted)     }      task.resume()   } } 

Playground example:

import Foundation import PlaygroundSupport  let page = PlaygroundPage.current page.needsIndefiniteExecution = true  let url = URL(string: "https://source.unsplash.com/random/4000x4000")! let task = URLSession.shared.dataTask(with: url) { _, _, _ in   page.finishExecution() }  // Don't forget to invalidate the observation when you don't need it anymore. let observation = task.progress.observe(\.fractionCompleted) { progress, _ in   print(progress.fractionCompleted) }  task.resume() 
like image 76
yas375 Avatar answered Sep 28 '22 08:09

yas375


you can use this code for showing download process with progress bar with its delegate functions.

import UIKit  class ViewController: UIViewController,NSURLSessionDelegate,NSURLSessionDataDelegate{      @IBOutlet weak var progress: UIProgressView!      var buffer:NSMutableData = NSMutableData()     var session:NSURLSession?     var dataTask:NSURLSessionDataTask?     let url = NSURL(string:"http://i.stack.imgur.com/b8zkg.png" )!     var expectedContentLength = 0       override func viewDidLoad() {         super.viewDidLoad()         progress.progress = 0.0         let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()         let manqueue = NSOperationQueue.mainQueue()         session = NSURLSession(configuration: configuration, delegate:self, delegateQueue: manqueue)         dataTask = session?.dataTaskWithRequest(NSURLRequest(URL: url))         dataTask?.resume()          // Do any additional setup after loading the view, typically from a nib.     }     func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveResponse response: NSURLResponse, completionHandler: (NSURLSessionResponseDisposition) -> Void) {          //here you can get full lenth of your content         expectedContentLength = Int(response.expectedContentLength)         println(expectedContentLength)         completionHandler(NSURLSessionResponseDisposition.Allow)     }     func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveData data: NSData) {           buffer.appendData(data)          let percentageDownloaded = Float(buffer.length) / Float(expectedContentLength)         progress.progress =  percentageDownloaded     }     func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?) {         //use buffer here.Download is done         progress.progress = 1.0   // download 100% complete     } } 
like image 30
Dharmesh Kheni Avatar answered Sep 28 '22 08:09

Dharmesh Kheni