'Prevent crash when view controller is switched during an api call swift

Hello I am making an app with api calls and switches viewcontrollers on a button click. The only issue is that when I click the back button when an api call is taking a couple seconds, the app crashes. Is there any way to catch this and prevent a crash? Thanks for any responses in advance!

Code to switch view controllers:

let transition = CATransition()
transition.duration = 0.3
transition.type = CATransitionType.push
transition.subtype = CATransitionSubtype.fromLeft
transition.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeInEaseOut)
self.view.window!.layer.add(transition, forKey: kCATransition)
let presentedVC = self.storyboard!.instantiateViewController(withIdentifier: "ViewController")
self.present(presentedVC, animated: false, completion: nil)


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source