NSURLSession, after the data task is converted to download task, it can't download in background
<p>If I run the following code and let the app in background, the download is still continuing. Finally, when the download is finished, I can get the right callback.</p>

<pre><code>let configuration = NSURLSessionConfiguration.backgroundSessionConfigurationWithIdentifier(SessionProperties.identifier)
let backgroundSession = NSURLSession(configuration: configuration, delegate: self.delegate, delegateQueue: nil)

let url = NSURLRequest(URL: NSURL(string: data[1])!)
let downloadTask = backgroundSession.downloadTaskWithRequest(url)
    downloadTask.resume()
</code></pre>

<p>But I have a requirement, that is I have to judge what the server returns to me, if it is a json, I don't do the download, so I want to get the response header first, then if it needs to download, I change the data task to download task, so I did as the following code</p>

<pre><code>let configuration = NSURLSessionConfiguration.backgroundSessionConfigurationWithIdentifier(SessionProperties.identifier)
let backgroundSession = NSURLSession(configuration: configuration, delegate: self.delegate, delegateQueue: nil)

let url = NSURLRequest(URL: NSURL(string: data[1])!)
//I change the downloadTaskWithRequest to dataTaskWithRequest
let downloadTask = backgroundSession.dataTaskWithRequest(url)
downloadTask.resume()
</code></pre>

<p>Then I can get the response header in the callback, and if it needs to download file, I can change the data task to download task, as following</p>

<pre><code>func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveResponse response: NSURLResponse, completionHandler: (NSURLSessionResponseDisposition) -&gt; Void) {
    if let response = response as? NSHTTPURLResponse {
        let contentType = response.allHeaderFields["Content-Type"] as! String
        if contentType == "image/jpeg" {
            //change the data task to download task
            completionHandler(.BecomeDownload)
            return
        }
    }
    completionHandler(.Allow)

}
</code></pre>

<p>So far so good. When I run the app in the foreground, the effect is like what I thought. But after the app runs in background, the download is stoped, then when I open the app, the console says "Lost connection to background transfer service".</p>

<p>I thought Apple is so smart, he gives us many useful callbacks, but now, I didn't know where I am wrong, and I also see the source code about the AFNetworking and Alamofire, but I didn't find the referring thing.</p>

<p>I also think it is a common requirement, but I can't find any helpful information on the internet, it is too odd. </p>

<p>So hope you can help me out, thanks a billion.</p>