0

I have a crash in my Swift 3 iOS app when I have an active URLSessionTask and the user presses the back button and the view controller is deinited. I call the cancel method on the urlsessiontask in the back button and no crash occurs at that time but when the user goes back to the view controller the app crashes. If the user allows the url session task to complete there is no crash. Does anyone know what I can do to prevent the crash? I am using iOS 10, Swift 3, Xcode 8. Thanks in advance.

Gregory Williams
  • 363
  • 3
  • 16

1 Answers1

1

Don't make the view controller the delegate of the URL session if it might not be around when the download completes.

Here's one solution:

Create a DownloadManager singleton that is the delegate of the URL session, saves the files to disk once the download is complete, records info about the file having been downloaded, and then notifies its delegate, using a weak delegate property.

(Some people believe that singletons are the root of all evil and should never be used. I'm not one of those people. To my mind an app-wide download manager is an excellent use-case for a singleton.)

Duncan C
  • 115,063
  • 19
  • 151
  • 241