iOS - First network request fails after unlock

Viewed 1989

I have an iOS app that pulls user data from the server in applicationDidBecomeActive.

If the user presses the home button, then returns to the app, either through the app icon or multitasking screen, the function works fine.

If the user locks the device in the mean time (either while still in the app or pressing home, then locking) the network request fails. I am using Alamofire. The response object is nil and the result.data is empty. There is no request logged on the server either. The failure happens instantly.

2 Answers

In applicationWillEnterForeground of AppDelegate initialize your Network Manager class again, and it will solve the problem. The reason for this issue is, when you lock your device, the OS locks the sockets and does not release it when the phone is unlocked. So please again initialize your network manager class and it will solve the problem.

     func applicationWillEnterForeground(_ application: UIApplication) {
            WebServiceManager.sharedInstance.sessionManr = Alamofire.SessionManager.default
            WebServiceManager.sharedInstance.sessionManr.session.configuration.requestCachePolicy = .reloadIgnoringLocalAndRemoteCacheData

            WebServiceManager.sharedInstance.sessionManr.session.configuration.urlCache = nil
            WebServiceManager.sharedInstance.sessionManr.session.configuration.timeoutIntervalForRequest =  180 //40
            WebServiceManager.sharedInstance.sessionManr.session.configuration.httpShouldSetCookies = true
     }
Related