MMWormwhole communication with the app in background

441 views Asked by At

I'm working on extension for the Apple Watch and I need to communicate with the containing app.

MMWormwhole seems like a nice approach for this type of communication. The problem is that my messages are not delivered to the containing app when it is running in background, when opened from openParentApplication.

Is there any way make the MMWormwhole to receive messages while in background mode?

2

There are 2 answers

6
John On BEST ANSWER

Yes, it is possible. But you have to ensure that the main app on the iPhone is not suspended before it can send its reply. This can be done by starting a background task in handleWatchKitExtensionRequest as specified in the documentation.

Code in the app delegate of the main app on iPhone:

- (void)application:(UIApplication *)application handleWatchKitExtensionRequest:(NSDictionary *)userInfo reply:(void ( ^)( NSDictionary * ))reply
{
   __block UIBackgroundTaskIdentifier watchKitHandler;
   watchKitHandler = [[UIApplication sharedApplication] beginBackgroundTaskWithName:@"backgroundTask"
                                                               expirationHandler:^{
                                                                 watchKitHandler = UIBackgroundTaskInvalid;
                                                               }];

   if ( [[userInfo objectForKey:@"request"] isEqualToString:@"getData"] )
   {
      // get data
      // ...
      reply( data );
   }

   dispatch_after( dispatch_time( DISPATCH_TIME_NOW, (int64_t)NSEC_PER_SEC * 1 ), dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0 ), ^{
       [[UIApplication sharedApplication] endBackgroundTask:watchKitHandler];
   } );
}
0
Timothy Sanders On

I use the wormhole the other way: communicating from the app to the watch extension. It seems likely that instead of using the wormhole you could pass your message in the userInfo parameter of the openParentApplication call you're already making.

However, if there's a complex reason where you want to pick up some other message or whatever you could manually check in the application: handleWatchKitExtensionRequest: reply: method. Something like:

    if let updatedMessage: AnyObject = wormhole.messageWithIdentifier(updatedKey) {
            processUpdatedWormholeMessage(updatedMessage)
    }

should work even when the app is in the background.