问题描述
我正尝试在didReceiveRemoteNotification方法中像POST,GET这样的后台进行呼叫,因为随着推送通知的到来,它们开始起作用。我的问题是,直到我打开应用程序,所有Alamofire.request才会在后台模式下调用。我现在有
I'm trying to make calls in background like POST,GET to be more precise in the didReceiveRemoteNotification method, because they start to work as a push notification arrive. My problem is that all the Alamofire.request are never call in Background mode until I open the app. I have by now
我正在尝试打开一个会话,但是它无法使请求正常工作。
Im was trying to open a session but it won't make the request work.
这些就是我要在后台执行的操作(手机在后台执行)
These is what i want to execute in background (cellphone in background)
Alamofire.Manager(configuration: configuration).request(.GET, url, parameters: nil)
.responseJSON { (_, _, JSON, _) in
//println(JSON)
println(JSON)
REST OF THE CODE
但是它不起作用,即使我在这些请求下面添加代码也可以,但是
But it won't work, even if i add code below these request it works but the return of the request or even the request is not made.
推荐答案
虽然方法说后台配置,但实际上是什么意思已将网络会话配置为上传/下载。相反,您需要做的是延长应用程序的执行时间,以便即使在后台也可以运行一段时间。
While method says "background configuration", what it actually means is that the network session is configured to allow for interruptions and continuation of upload / download. What you need to do instead is to extend execution time of the application so it works for some time even in background
有 beginBackgroundTaskWithExpirationHandler:
专门用于执行此操作。使用它时,您将有几分钟的时间来执行所需的任何操作(在此限制之后,无论如何您的应用程序都将被终止,现在您的应用程序将立即终止)。
There is beginBackgroundTaskWithExpirationHandler:
that is specifically designed to do that. When you use it, you will get few more minutes to execute whatever you need (after that limit, your application will get terminated no matter what, now your application is terminated immediately).
您可以编写以下方法:
func beginBackgroundTask() -> UIBackgroundTaskIdentifier {
return UIApplication.sharedApplication().beginBackgroundTaskWithExpirationHandler({})
}
func endBackgroundTask(taskID: UIBackgroundTaskIdentifier) {
UIApplication.sharedApplication().endBackgroundTask(taskID)
}
要使用它,您只需简单的开始/结束开始/结束下载调用时的任务:
When you want to use it, you just simple begin / end the task when starting / finishing the download call:
// Start task
let task = self.beginBackgroundTask()
// Do whatever you need, like download of the images
self.someBackgroundTask()
...
// End task once everything you need to do is done
self.endBackgroundTask(task)
希望
编辑1:
如果问题是从未调用过您的下载方法,则它将表示您没有在通知有效负载中发送正确的数据:
If the problem is that your download method IS NEVER called, then it means you are not sending proper data in notification payload:
这篇关于后台请求无法执行Alamofire Swift的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!