Notify WatchKit app of an update without the watch app requesting it

前端 未结 4 1479
天涯浪人
天涯浪人 2020-12-07 16:20

I\'m aware of the capabilities of WKInterfaceController openParentApplication and handleWatchKitExtensionRequest methods for the watch app to open

4条回答
  •  北海茫月
    2020-12-07 16:40

    The answer by Ivp above is a nice one. However, I would like to add that using notifications can be tricky and I would like to share my experiences.

    First, I added the observers in the method "awakeWithContext". Problem: The notifications were given several times. So, I added "removeObserver:self" before adding an observer. Problem: the observer will not be removed when "self" is different. (See also here.)

    I ended up putting the following code in "willActivate":

    // make sure the the observer is not added several times if this function gets called more than one time
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"com.toWatch.todo.updated" object:nil];
    CFNotificationCenterRemoveObserver( CFNotificationCenterGetDarwinNotifyCenter(), (__bridge const void *)( self ), CFSTR( "NOTIFICATION_TO_WATCH_TODO_UPDATED" ), NULL );
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector( didReceivedNSNotificationTodo ) name:@"com.toWatch.todo.updated" object:nil];
    CFNotificationCenterAddObserver( CFNotificationCenterGetDarwinNotifyCenter(), (__bridge const void *)( self ), didReceivedDarwinNotificationTodo, CFSTR( "NOTIFICATION_TO_WATCH_TODO_UPDATED" ), NULL, CFNotificationSuspensionBehaviorDrop );
    

    I also added the following to "didDeactivate":

    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"com.toWatch.todo.updated" object:nil];
    CFNotificationCenterRemoveObserver( CFNotificationCenterGetDarwinNotifyCenter(), (__bridge const void *)( self ), CFSTR( "NOTIFICATION_TO_WATCH_TODO_UPDATED" ), NULL );
    

    If a notification is sent to the Watch app while it is inactive, this notification is not delivered.

    So, in addition to the notification mechanism above, which can inform the active Watch app of a change done on the iPhone, I use NSUserDefaults and a common app group (more info) to save information. When the controller on the Watch gets active, it checks the NSUserDefaults and updates the view if necessary.

提交回复
热议问题