Search code examples
iosobjective-cwatchkitwatchos-2

WCSession didReceiveUserInfo gets called but iPhone app stops background activity


I'm experiencing issues with my watchOS 2 app. I'm using [[WCSession defaultSession] transferUserInfo:request] to transfer a dictionary of data to my iPhone app.

In AppDelegate.m in the iPhone app I have implemented -(void)session:(WCSession *)session didReceiveUserInfo:(NSDictionary<NSString *,id> *)userInfo

When I send a transfer request from my watch, this method gets called (confirmed by a NSLog I created), but not all code is executed. To be more specific, it calls the following method to post to Facebook, which also gets called but which will not be completely executed.

- (void)postToFacebook:(NSString*)postMessage {

NSLog(@"begin");

    if ([[FBSDKAccessToken currentAccessToken] hasGranted:@"publish_actions"]) {

        [[[FBSDKGraphRequest alloc] initWithGraphPath:@"me/feed" parameters:@{@"message" : postMessage, @"privacy": @"{'value': 'SELF'}"}  HTTPMethod:@"POST"] startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) {

            NSLog(@"done");

        }];

    }

}
}

NSLog "begin" is shown, but NSLog "done" isn't shown.

I've tested running the method from my iPhone and everything is working fine. But when I try to call it from the watch using transferUserInfo, it isn't executed properly.

Now my question is, how I can assure that the background task within the iPhone app isn't killed before the method is completely done.


Solution

  • A bit of a long shot, but try wrapping the code in a dispatch to the main queue:

    - (void)postToFacebook:(NSString*)postMessage {
        dispatch_sync(dispatch_get_main_queue(), ^{
            if ([[FBSDKAccessToken currentAccess...etc...
        });
    }