Reputation: 312
I have a confusion. As per my understanding , Delegates and Completion Handler are two different mechanism and one can implement NSURLSession using either. But why does the below delegate does not get called
(void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)aresponse
but this gets called
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)aresponse
completionHandler:(void (^)(NSURLSessionResponseDisposition disposition))completionHandler
Similar for didReceiveChallenge.
When
(void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data
can get called , then what is the need to explicitly add completion handler for didRecieveResponse.
Is it indeed not required or is the way it is to be?
Could you please explain what is the purpose of adding completion handler above and in general?
Upvotes: 0
Views: 1805
Reputation: 6504
See the docs for the NSURLSessionDataDelegate and in particular the note:
NOTE
An NSURLSession object need not have a delegate. If no delegate is assigned, when you create tasks in that session, you must provide a completion handler block to obtain the data.
Completion handler block are primarily intended as an alternative to using a custom delegate. If you create a task using a method that takes a completion handler block, the delegate methods for response and data delivery are not called.
So if the completion handler method is used the NSURLSessionDataDelegate
is not active but the NSURLSessionDelegate
and the NSURLSessionTaskDelegate
may be.
The delegate approach is best if you have complex handling of the connection, such as wanting to use it as a streaming connection using the data before completion or other complicated handling. You will need to define and create an object to handle the task, tracking state and what should be done with the data once received. You will also need to retain this object. A single object could handle multiple connections but that would also be complexity that you would need to handle.
The callback/closure/block approach allows all the logic for handling the response and the data to be defined right where the request is made with all the state from the time of the request captured if you need it in the closure. If your requirements are simple it will often be the best approach in my view due to the benefits of keeping the code together and not needing to worry about multiple tasks and their states.
Upvotes: 1