---
title: "#77: Background Downloads ⏳"
url: https://littlebitesofcocoa.com/77-background-downloads
author: Jake Marsh
published: 2015-09-08
topics: ["Foundation","Networking","Multitasking"]
description: "Imagine an app that downloads and plays movies. If a user begins downloading a movie, it'd be great if the file could continue downloading even if the user..."
---

# #77: Background Downloads ⏳

By Jake Marsh, September 8, 2015. HTML: https://littlebitesofcocoa.com/77-background-downloads

Imagine an app that downloads and plays movies. If a user begins downloading a movie, it'd be great if the file could continue downloading even if the user presses the **home button** and sends the app to the background. _NSURLSessionDownloadTask_ can help. Let's take a look.

First we create a new **background configuration** and **session**. Then we use that **session** to create a new **download task**:

``` swift
class ViewController: UIViewController, NSURLSessionDownloadDelegate, NSURLSessionTaskDelegate {
    func downloadMovieFile() {
    let configuration = NSURLSessionConfiguration.backgroundSessionConfigurationWithIdentifier("downloads-session")
    let session = NSURLSession(configuration: configuration, delegate: self, delegateQueue: nil)

    let task = session.downloadTaskWithURL(NSURL(string: "http://supersecret.disney.com/movies/episodeVII.mp4")!)
    task.resume()
  }
}
```

We can grab the downloaded **data** pretty easily, by implementing this **function** from **NSURLSessionDownloadDelegate**:

``` swift
func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didFinishDownloadingToURL location: NSURL) {
    print("Movie data written to \(location)")
}
```

Last but not least, we'll need to implement a **function** from **NSURLSessionTaskDelegate**. In it we'll call `finishTasksAndInvalidate` on the **session**. This ensures everything is cleaned up and the **session** lets go of us (`self`) as its **delegate**.

``` swift
func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?) {
  if let error = error { print("Download Error: \(error)") }
  session.finishTasksAndInvalidate()
}
```
