Rob's answer is correct and gave me a big clue. However - for my specific problem - it didn't jump out at me why the NSURLSessionTaskDelegate
methods might not be called. If I could be allowed to provide another answer with a different focus.
Many of the NSURLSession
task creation methods have two variations; one with a completionHandler
parameter and one without.
For example:
func dataTaskWithRequest(_ request: NSURLRequest) -> NSURLSessionDataTask
func dataTaskWithRequest(_ request: NSURLRequest, completionHandler completionHandler: (NSData?, NSURLResponse?, NSError?) -> Void) -> NSURLSessionDataTask
If the completionHandler
method is used, then any delegate methods - in this case for NSURLSessionTaskDelegate
will be ignored. That's despite the fact that a delegate has been specified in the NSURLSession
initialiser.
The following Playground code demonstrates this. Toggle the task
declaration comments to see the delegate called or not:
import UIKit
import XCPlayground
XCPlaygroundPage.currentPage.needsIndefiniteExecution = true
class MyDelegate:NSObject, NSURLSessionTaskDelegate
{
func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?) {
NSLog("Delegate called")
}
}
let myDel = MyDelegate()
let config = NSURLSessionConfiguration.defaultSessionConfiguration()
let session = NSURLSession(configuration: config, delegate: myDel, delegateQueue: NSOperationQueue())
let url = NSURL(string: "http://httpbin.org")
let request: NSURLRequest = NSURLRequest(URL: url!)
// With completionHandler, delegate method above NOT called
let task : NSURLSessionDataTask = session.dataTaskWithRequest(request, completionHandler: {(data, response, error) in
NSLog("Task done")
})
// Without completionHandler, delegate method above IS called
//let task : NSURLSessionDataTask = session.dataTaskWithRequest(request)
task.resume()
TLDR: tearing your hair out wondering why the NSURLSession
's delegate methods aren't called? User the alternative method signature to create your session tasks; that which omits the completionHandler parameter.