1

I try to download a file in swift using NSURLSession: My delegates are never called and I don't know why. Can somebody help ?

Code: My Class has following protocols:

class ViewController: UIViewController, NSURLSessionDelegate {

In my Class I have a download zip function:

func download_zip(sURL: String, sToLocation: String) {

    var delegate = self;
    delegate.storePath=sToLocation;
    delegate.progressView=progressView;
    struct SessionProperties {
        static let identifier : String! = "url_session_background_download"
    }
    var configuration = NSURLSessionConfiguration.backgroundSessionConfigurationWithIdentifier(SessionProperties.identifier)
    var backgroundSession = NSURLSession(configuration: configuration, delegate: delegate, delegateQueue: nil)
    var url = NSURLRequest(URL: NSURL(string: sURL)!)
    var downloadTask = backgroundSession.downloadTaskWithRequest(url)
    downloadTask.resume()

}

In my Class I have some delegate functions:

//MARK: session delegate
func URLSession(session: NSURLSession, didBecomeInvalidWithError error: NSError?) {
    println("session error: \(error?.localizedDescription).")
}

func URLSession(session: NSURLSession, didReceiveChallenge challenge: NSURLAuthenticationChallenge, completionHandler: (NSURLSessionAuthChallengeDisposition, NSURLCredential!) -> Void) {
    completionHandler(NSURLSessionAuthChallengeDisposition.UseCredential, NSURLCredential(forTrust: challenge.protectionSpace.serverTrust))
}

func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didFinishDownloadingToURL location1: NSURL) {
    println("session \(session) has finished the download task \(downloadTask) of URL \(location1).")


}

func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
    println("session \(session) download task \(downloadTask) wrote an additional \(bytesWritten) bytes (total \(totalBytesWritten) bytes) out of an expected \(totalBytesExpectedToWrite) bytes.")


}

func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didResumeAtOffset fileOffset: Int64, expectedTotalBytes: Int64) {
    println("session \(session) download task \(downloadTask) resumed at offset \(fileOffset) bytes out of an expected \(expectedTotalBytes) bytes.")
}

func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?) {
    if error == nil {
        println("session \(session) download completed")
    } else {
        println("session \(session) download failed with error \(error?.localizedDescription)")
    }
}

func URLSessionDidFinishEventsForBackgroundURLSession(session: NSURLSession) {
    println("background session \(session) finished events.")

    if !session.configuration.identifier.isEmpty {
        callCompletionHandlerForSession(session.configuration.identifier)
    }
}

//MARK: completion handler
func addCompletionHandler(handler: CompleteHandlerBlock, identifier: String) {
    handlerQueue[identifier] = handler
}

func callCompletionHandlerForSession(identifier: String!) {
    var handler : CompleteHandlerBlock = handlerQueue[identifier]!
    handlerQueue!.removeValueForKey(identifier)
    handler()
}

No delegate function is called. Does anyone see the problem ?

mcfly soft
  • 11,289
  • 26
  • 98
  • 202
  • Does NSURLSessionDownloadDelegate subclasses NSURLSessionDelegate? – Leonardo May 29 '15 at 12:56
  • Did you set the delegates from NSURLSessionDelegate and NSURLSessionDownloadDelegate to your class? – Icaro May 29 '15 at 12:58
  • Thanks for helping. Sorry for the confusion. The protocoll NSURLSessionDownloadDelegate was one of my tries. I will update the question and remove this. I guess there is no need of this protocoll. – mcfly soft May 29 '15 at 13:02
  • In the meanwhile it works. But I don't know why. I played around and I guess I didn't change anything. What shall I do with the question ? – mcfly soft May 29 '15 at 15:24
  • dont you miss the NSURLSessionDownloadDelegate class protocol ? – SKYnine Jul 15 '15 at 15:15
  • Very similar to [Sam Wang's code](https://github.com/samwang0723/URLSessionBackgroundDownload/blob/master/URLSessionBackgroundDownload/DownloadSessionDelegate.swift) may be worth looking at how he makes similar calls in [this article](https://medium.com/swift-programming/learn-nsurlsession-using-swift-part-2-background-download-863426842e21#.cb5lme3z4) – dumbledad Jul 29 '16 at 09:33

2 Answers2

1

You have:

var backgroundSession = NSURLSession(configuration: configuration, delegate: delegate, delegateQueue: nil)

It should be:

var backgroundSession = NSURLSession(configuration: configuration, delegate: self, delegateQueue: NSOperationQueue.mainQueue())

Delegate had to be set to self. Also add "NSURLSessionDataDelegate" to the protocol.

0

Try storing the NSURLSession into a property, I think your session might be being cleared from the memory by ARC

Leonardo
  • 1,740
  • 18
  • 27