2

Currently I'm working on implementing a network manager for handling download and upload tasks. I have a class that confirms to URLSessionDownloadDelegate, URLSessionDelegate. The problem I'm facing is I'm using a single session object which is used for all the service calls. So when multiple network operations are being processed, all the response call backs will be handled in the class that is implementing the delegate methods. So to find for which call a response has been arrived, I'm comparing the task parameter of the delegate method and all the tasks that are running currently(I have closure property for each of the delegate methods in the class that confirms to session protocols). Is there any other ways to achieve this result ?(I think this won't be a good solution when handling large number of requests)

rmaddy
  • 314,917
  • 42
  • 532
  • 579
jegadeesh
  • 875
  • 9
  • 22
  • 1
    "I think this won't be a good solution when handling large number of requests", why not? – Ahmad F Jul 17 '17 at 12:15
  • what if the more then one request's call back comes in at the same time? – jegadeesh Jul 17 '17 at 12:18
  • 1
    The desired delegate method should be called based on what's the number of requests... the debug won't be that easy, but it should work as expected. – Ahmad F Jul 17 '17 at 12:22
  • 1
    @jegadeesh this could also happen with any other implementation of asynchronous networking, and has nothing to do with NSURLSession in particular. It is your job to provide thread-safety when mutating shared data. – Dmitry Serov Jul 17 '17 at 12:23
  • 1
    Related: https://stackoverflow.com/questions/24173210/implement-delegate-with-closure-in-swift – Ahmad F Jul 17 '17 at 12:24
  • I'll add some code and then it'll be easier for you to understand what I'm concerned about. – jegadeesh Jul 17 '17 at 12:26
  • @DmitrySerov Oh okey.. I'll explore on that then, thanks. – jegadeesh Jul 17 '17 at 12:28
  • @AhmadF the link you referred, I have tried implementing that already and now went in with another pattern as I faced few issues on that. But that pattern was a good one as it can have a delegate class for each request. Thanks for the time.. glad to here more pointers if any. – jegadeesh Jul 17 '17 at 12:31

1 Answers1

1

Ideally, you shouldn't be doing comparisons yourself, but rather should store the closures in a dictionary keyed by the task objects. Be sure to update the dictionary in any delegate methods that replace one task with another. And be sure to do dictionary lookups and stores on the same thread or serial queue every time.

dgatwood
  • 10,129
  • 1
  • 28
  • 49