Code: Select all
class ViewController: UIViewController, NSURLSessionDownloadDelegate {
private let MY_URL = "http://ipv4.download.thinkbroadband.com/200MB.zip"
private var downloadTask: NSURLSessionDownloadTask?
define a button to run our task
Code: Select all
@IBAction func DownloadAction(sender: AnyObject) {
createDownloadTask()
}
The real task
Code: Select all
func createDownloadTask() {
let downloadRequest = NSMutableURLRequest(URL: NSURL(string: MY_URL)!)
let session = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration(), delegate: self, delegateQueue: NSOperationQueue.mainQueue())
downloadTask = session.downloadTaskWithRequest(downloadRequest)
downloadTask!.resume()
}
define the delegates
Code: Select all
func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
let progress = Float(totalBytesWritten) / Float(totalBytesExpectedToWrite)
PercText.text = String(progress) + " [Total=" + String(totalBytesWritten) + "|" +
String(totalBytesExpectedToWrite) + "]"
}
to be called when the trasnsfer is complete
Code: Select all
func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didFinishDownloadingToURL location: NSURL) {
PercText.text = "Download finished"
}
Code: Select all
func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?) {
if let _ = error {
PercText.text = "Download failed"
} else {
PercText.text = "Download finished"
}
}
}