Background Transfer Service Continued ..2

This is second post in series. We implement the protocol method URLSessionDidFinishEventsForBackgroundURLSession that is called when app is in background and NSURLSession(Background mode configuration) is finished. This was my assumption. To check visually I was posting local notification from this method. I started observation and was surprised to find that it wasn’t getting called. I thought maybe my service didn’t complete but it did complete.

I checked the documentation again and found this that proved my assumption wrong.
In iOS, when a background transfer completes or requires credentials, if your app is no longer running, your app is automatically relaunched in the background, and the app’s UIApplicationDelegate is sent an application:handleEventsForBackgroundURLSession:completionHandler: message.

I forcefully quit the app by removing it from app switcher. I received the local notification that was called from the delegate method. I guess this is called when app is not running. If somehow app is still awake when you put app in background then URLSessionDidFinishEventsForBackgroundURLSession isn’t called so you will need to handle that in general finish delegate method of your session. I may be wrong.

- (void)URLSessionDidFinishEventsForBackgroundURLSession:(NSURLSession *)session {
    if (self.backgroundTransferCompletionHandler) {
        void (^completionHandler)() = self.backgroundTransferCompletionHandler;
        self.backgroundTransferCompletionHandler = nil;
-(void)application:(UIApplication *)application handleEventsForBackgroundURLSession:(NSString *)identifier completionHandler:(void (^)())completionHandler{
    self.backgroundTransferCompletionHandler = completionHandler;
    [self sendLocalNotificationWithMessage:@"Checked In"];


One Comment

Join the Discussion

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>