iOS - First network request fails after unlock

Apple Tech Note TN2277, says that the kernel can reclaim sockets out from under apps without them having any idea what happens. Here's the relevant part :

Testing Socket Reclaim

If you're going to write code that handles a socket's resources being reclaimed by the kernel, you have to figure out how to test it. The exact circumstances under which the system might reclaim a socket's resources are purposely not documented; this gives us the flexibility to improve things in the future. However, on current systems (iOS 4.0 through iOS 4.3), you can get the system to reclaim resources from the sockets in your app by:

  1. putting your app in the background
  2. ensuring that the app is suspended
  3. locking the screen

When your app resumes execution it will find that it's sockets have been reclaimed.

To workaround this, try to create new Alamofire.Manager whenever my AppDelegate's applicationWillEnterForeground is called. Hope this helps you..


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
     }