进入后台时,Alamofire 请求卡住了? [英] Alamofire request gets stuck when entering background?

查看:37
本文介绍了进入后台时,Alamofire 请求卡住了?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Alamofire 调用需要很长时间加载的网络服务.如果应用程序进入后台,当我返回应用程序时,我会被加载器卡住.我想这是因为调用永远不会向我的完成处理程序返回任何内容.我该如何解决这个问题?

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?

推荐答案

您可以使用后台抓取来解决这个问题.在 Swift 3 中可以通过以下方式完成:

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
    }

在此线路后致电您的 alamofire 服务.在完成处理程序中,使用以下几行结束任务.

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

请注意,应用在进入非活动状态之前还有一些后台时间(backgroundTimeRemaining 属性).你必须在那之前完成你的任务.在剩余后台时间达到零之前不久调用处理程序.此外,对方法 beginBackgroundTask(withName:){} 的每次调用都必须通过对 endBackgroundTask: 方法的匹配调用来平衡.

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

之后,转到您的 info.plist 文件,并将其作为 Source 打开以添加以下代码.

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

这篇关于进入后台时,Alamofire 请求卡住了?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆