2

I am creating an NSURLSession on init of a class with the following code:

dispatch_once(&Static.token) { [unowned self] in
        let configuration = NSURLSessionConfiguration.backgroundSessionConfigurationWithIdentifier(CONSTANTS.BackgroundSessionUploadIdentifier)
        Static.session = NSURLSession(configuration: configuration, delegate: self, delegateQueue: nil)
    }

After it completes the class isn't being deinited and any future uploads' callbacks have the first class instantiation as their self. How do I properly cleanup an NSURLSession once my upload completes?

My entire class can be seen here:

https://gist.github.com/aishowdown/e88f6595e5a23d936e29

QuinnBaetz
  • 559
  • 9
  • 23

1 Answers1

9

call

session.finishTasksAndInvalidate(), the session will be destroyed after the last task finishes.

or

session.invalidateAndCancel(), the session will be destroyed immediately

nRewik
  • 8,958
  • 4
  • 23
  • 30
  • Though it's now deiniting, new instances get an invalidated session. Should I remove the dispatch_once line so that each instance gets it's own session? Or would it be better to just allow the first instance to stay alive to handle future work? – QuinnBaetz Aug 07 '15 at 02:03
  • It depends on whether you want the uploader to be a single central uploader, or many instances of uploader. In this case, I would remove `dispatch_once` and each uploader will get it's own session. – nRewik Aug 07 '15 at 02:11
  • You've been a lot of help so far, but things are still acting wonky. It seems like the previous sessions are polluting the current one, and none of the uploads after the first work and the progress bar jumps around. Any ideas what would cause that? https://gist.github.com/aishowdown/e88f6595e5a23d936e29 – QuinnBaetz Aug 07 '15 at 07:04
  • As I see from your code, you update progress via `NotificationCenter`, So make sure you track the correct `Notification`, because all uploader emit progress change on the same `NotificationCenters.UploadPercentage`. If you don't want to use delegate pattern, so make the name like `Upload1` and `Upload2` – nRewik Aug 07 '15 at 07:39
  • Shouldn't we also cleanup cache as part of session cleanup? Maybe it's better to use `session.reset {}` instead? – Legonaftik Nov 27 '20 at 12:29