Alamofire request gets stuck when entering background?

橙三吉。 提交于 2021-02-18 22:37:12

问题


I'm using Alamofire to make a call to a webservice which takes a pretty long time to load. If the app goes into the background I get stuck with my loader when I return to the app. I imagine it's because the call never returns anything to my completion handler. How can I address this problem?


回答1:


You can use background fetching to solve this problem. It can be done in the following way in Swift 3:

    var backgroundTask: UIBackgroundTaskIdentifier? // global variable        

    backgroundTask = UIApplication.shared.beginBackgroundTask(withName: "backgroundTask") {
        // Cleanup code should be written here so that you won't see the loader

        UIApplication.shared.endBackgroundTask(self.backgroundTask!)
        self.backgroundTask = UIBackgroundTaskInvalid
    }

Call your alamofire service after this line. In the completion handler, end the task using the below lines.

    UIApplication.shared.endBackgroundTask(self.backgroundTask!)
    self.backgroundTask = UIBackgroundTaskInvalid

Please note that the app has some background time (backgroundTimeRemaining property) remaining before it enters the inactive state. You have to get your task done before that time. The handler is called shortly before the remaining background time reaches zero. Also, each call to the method beginBackgroundTask(withName:){} must be balanced by a matching call to the endBackgroundTask: method.

To make the code given above work, you need to adjust settings in your app. Go to "Targets" and click on "Capabilities" to make the following changes

After that, go to your info.plist file, and open it as Source to add the following code.

I hope this helps you. If you need more detailed information, these links might help

  • https://developer.apple.com/reference/uikit/uiapplication/1623031-beginbackgroundtaskwithexpiratio
  • https://developer.apple.com/reference/uikit/uiapplication/1622970-endbackgroundtask



回答2:


The problem can be solved by adding:

application.beginBackgroundTask { }

into func applicationDidEnterBackground(_ application: UIApplication) and

application.endBackgroundTask(.invalid)

into func applicationWillEnterForeground(_ application: UIApplication)



来源:https://stackoverflow.com/questions/40206853/alamofire-request-gets-stuck-when-entering-background

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!