I have an app that listens to silent push notifications from my server while being in the background (via didReceiveRemoteNotification
) to perform some network operations using URLSession.data.task
. I’m new to Swift and I’m working on an existing codebase that nests multiple requests when a push is received in this fashion:
URLSession.shared.dataTask(with: request) {data, response, error in
//do some others URLSession.shared.dataTask operations
}.resume()
My didReceiveRemoteNotification
looks like this:
func application(_ application: UIApplication,
didReceiveRemoteNotification userInfo: [AnyHashable: Any],
fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
handlePush(userInfo: userInfo, metric: Metric.ALAPPBGPushFetchRequested)
completionHandler(UIBackgroundFetchResult.noData)
}
The Problem, when the silent push is received,completionHandler
is called before all other URLSessions
are completed. Ideally, I would have to call completionHandler
from within those URLSession
once those requests are resolved. I cannot just pass the reference of the completionHandler
because there isn’t a direct hierarchy that allows me to pass it down (handlePush
triggers some other listeners, etc).
What could be a good solution to use this completionHandler
from a different scope other than the original one? I thought about storing the completionHandler
in a global variable and then using it but I’m getting unexpected exceptions sometimes, does not seems reliable, unless I’m just doing poor swift. I also wouldn’t want to refactor the chain of calls that happens after handlePush
because most of them are sensor listeners that eventually calls those URLSession
.