I am trying to send a notification from my iPhone to the Watch device using
CFNotificationCenterAddObserver
on the watch and CFNotificationCenterPostNotification
.(I am NOT testing on the Xcode simulator).
This is my code in the iOS app:
#include <CoreFoundation/CoreFoundation.h>
...
- (void)sendLogOutNotificationToWatch{
dispatch_async(dispatch_get_main_queue(), ^{
CFNotificationCenterPostNotification(CFNotificationCenterGetDarwinNotifyCenter(), CFSTR("NOTIFICATION_TO_WATCH"), (__bridge const void *)(self), nil, TRUE);
});
}
And this is how I use it on the apple watch extension app:
@implementation InterfaceController
.....
- (void)awakeWithContext:(id)context {
[super awakeWithContext:context];
....
[self registerToNotification];
}
- (void)registerToNotification
{
[[NSNotificationCenter defaultCenter] removeObserver:self name:@com.test.app" object:nil];
CFNotificationCenterRemoveObserver( CFNotificationCenterGetDarwinNotifyCenter(), (__bridge const void *)( self ), CFSTR( "NOTIFICATION_TO_WATCH" ), NULL );
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(userLoggedOut ) name:@"com.test.app" object:nil];
CFNotificationCenterAddObserver( CFNotificationCenterGetDarwinNotifyCenter(), (__bridge const void *)( self ), didReceivedDarwinNotification, CFSTR( "NOTIFICATION_TO_WATCH" ), NULL, CFNotificationSuspensionBehaviorDrop );
}
void didReceivedDarwinNotification()
{
[[NSNotificationCenter defaultCenter] postNotificationName:@"com.test.app" object:nil];
}
- (void)didDeactivate {
[super didDeactivate];
[[NSNotificationCenter defaultCenter] removeObserver:self name:@"com.test.app" object:nil];
CFNotificationCenterRemoveObserver( CFNotificationCenterGetDarwinNotifyCenter(), (__bridge const void *)( self ), CFSTR( "NOTIFICATION_TO_WATCH" ), NULL );
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (void)userLoggedOut{
[self showAlertViewwithTitle:@"Notice" andMessage:@"User logged out on iPhone device!"];
}