Reputation: 421
I am not sure how to prevent an error in my app. I need to call a server using URLSession.shared.dataTask which works perfectly fine if I allow it to complete. However, if I pop the uiviewcontroller off the stack before the URLSession.shared.dataTask has completed a run time error occurs because the viewcontroller no long exists. It occurs in different places in the json parsing and network call. Usually in the call back or the displaying of an error if the network call fails. Does anyone know how to either stop the network call when the uiviewcontroller deinits or detect in the network call code that the uiviewcontroller has disappeared so I don't call the callback. I am using Xcode 8 and iOS 10 with Swift 3. Thanks.
Upvotes: 1
Views: 194
Reputation:
Before you pop your VC, call these:
[dataTask cancel]
dataTask = nil // if needed
(you might need to convert o Swift, since these are in Obj-c but you get the idea)
If you want you can also detect if it is the last VC you are popping and do this accordinly in the viewWillDisappear
method if you wish.
Upvotes: 2