Background request not running Alamofire Swift

I try to make calls in the background, such as POST, GET, to be more precise in the didReceiveRemoteNotification method, because they start working as a push notification. My problem is that all Alamofire.request never rings in the background until I open the application. I'm by now

Im trying to open a session, but it will not make the request work.

This is what I want to run in the background (cell phone in the background)

Alamofire.Manager(configuration: configuration).request(.GET, url, parameters: nil) .responseJSON { (_, _, JSON, _) in //println(JSON) println(JSON) REST OF THE CODE 

But this will not work, even if I add the code below this request, it works, but the request is returned or even the request is not executed.

+7
swift uiapplicationdelegate alamofire
source share
1 answer

While the method says “background configuration”, which actually means that the network session is configured to allow interruptions and continued download / download. Instead, you need to increase the runtime of the application so that it runs for a while even in the background

There is beginBackgroundTaskWithExpirationHandler: specifically designed for this. When you use it, you will get a few more minutes to complete everything you need (after this restriction, your application will be terminated no matter what your application is now terminated immediately).

You can write the following methods:

 func beginBackgroundTask() -> UIBackgroundTaskIdentifier { return UIApplication.sharedApplication().beginBackgroundTaskWithExpirationHandler({}) } func endBackgroundTask(taskID: UIBackgroundTaskIdentifier) { UIApplication.sharedApplication().endBackgroundTask(taskID) } 

When you want to use it, you just start / end the task when you start / end 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) 

Hope this helps!

Change 1:

If the problem is that your download method has NEVER called, then you are not sending the proper data to the notification payload:

For a push notification to start the download operation, the notification payload must include a key that is accessible for content, with its value set to 1. When this key is present, the system wakes the application in the background (or launches it in the background) and calls the application delegates : didReceiveRemoteNotification: fetchCompletionHandler: method. Your implementation of this method should download the appropriate content and integrate it into your application. https://developer.apple.com/library/content/documentation/iPhone/Conceptual/iPhoneOSProgrammingGuide/BackgroundExecution/BackgroundExecution.html

+14
source share

All Articles