Background request not execute Alamofire Swift

|▌冷眼眸甩不掉的悲伤 提交于 2019-11-28 09:23:52
Jiri Trecak

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

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