Search code examples
ioswatchkitios-extensionsmmwormhole

MMWormwhole communication with the app in background


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?


Solution

  • 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];
       } );
    }