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
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).
You can write 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 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)
Hope it helps!
Edit 1:
If the problem is that your download method IS NEVER called, then it means you are not sending proper data in notification payload:
For a push notification to trigger a download operation, the notification’s payload must include the content-available key with its value set to 1. When that key is present, the system wakes the app in the background (or launches it into the background) and calls the app delegate’s application:didReceiveRemoteNotification:fetchCompletionHandler: method. Your implementation of that method should download the relevant content and integrate it into your app. https://developer.apple.com/library/content/documentation/iPhone/Conceptual/iPhoneOSProgrammingGuide/BackgroundExecution/BackgroundExecution.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With