Method NSURLSessionDataDelegate didReceiveData and others are not called

I had a problem from which didReceiveData and didCompleteWithError are not being 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="+" rabcd@gmail.com &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 the delegates that 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 looked with break points

didReceiveResponse is called, but the other two are not called.

Please, help!

+6
source share
2 answers

Deploy the completion handler in the 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 } 
+12
source

I will confirm ChezhianNeo's comment on calling the delegate didRecieveResponse with NSURLSessionResponseAllow, as shown below

 - (void) URLSession:(NSURLSession *)session dataTask: (NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler { completionHandler(NSURLSessionResponseAllow); } 

It also allowed to call the didRecieveData delegation method.

Which also works, at least for me, it’s just not to implement the didReceiveResponse method in your delegate, but to implement the didReceiveData method - to β€œskip” the didReceiveResponse method allows you to call the didReceiveData method, which does not seem to make much sense, but it works.

+3
source

Source: https://habr.com/ru/post/980671/


All Articles