NSURLSessionDataDelegate method didReceiveData and others are not called

Ria Bhattacharjee picture Ria Bhattacharjee · Jan 7, 2015 · Viewed 7.7k times · Source

I am having a problem that didReceiveData and didCompleteWithError are not called. Here is my code :

class LoginViewController: UIViewController, NSURLSessionDataDelegate, NSURLSessionDelegate, NSURLSessionTaskDelegate {
.
.
.
}

@IBAction func loginAction(sender: AnyObject) {

    var sessionConfiguration = NSURLSessionConfiguration.defaultSessionConfiguration()

    var session = NSURLSession(configuration: sessionConfiguration, delegate: self, delegateQueue:nil)

    let postParams = "email="+"[email protected]&password="+"abcd"

    let url = NSURL(string:"http://myurl.com/api/v1/user/login")
    let request = NSMutableURLRequest(URL: url!)

    request.HTTPMethod = "POST"

    request.HTTPBody = postParams.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)

    let task = session.dataTaskWithRequest(request)


    task.resume()


}

These are delegates I implemented

func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveResponse response: NSURLResponse, completionHandler: (NSURLSessionResponseDisposition) -> Void) {

}

func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveData data: NSData) {

}

func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?) {

}

Here I watched with break points

didReceiveResponse is called but other two are not getting called.

Please help !

Answer

ChezhianNeo picture ChezhianNeo · Mar 4, 2015

Implement the completion handler in your delegate method

func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveResponse response: NSURLResponse, completionHandler: (NSURLSessionResponseDisposition) -> Void) {
completionHandler(NSURLSessionResponseDisposition.Allow) //.Cancel,If you want to stop the download
}