我正在尝试使用以下方式将通知从iPhone发送到Watch设备
手表上的CFNotificationCenterAddObserverCFNotificationCenterPostNotification。(我不在Xcode模拟器上进行测试)。

这是我在iOS应用中的代码:

#include <CoreFoundation/CoreFoundation.h>
...
- (void)sendLogOutNotificationToWatch{
    dispatch_async(dispatch_get_main_queue(), ^{
        CFNotificationCenterPostNotification(CFNotificationCenterGetDarwinNotifyCenter(), CFSTR("NOTIFICATION_TO_WATCH"), (__bridge const void *)(self), nil, TRUE);
    });
}


这就是我在Apple Watch扩展应用上使用它的方式:

@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!"];
}

最佳答案

您应该使用WatchConnectivity将消息从iPhone发送到Apple Watch。

Watch和iPhone上的API几乎相同。如果您的手表应用未运行,或者屏幕关闭,则应使用transferUserInfo。如果您的手表应用程序正在运行并且屏幕打开,则可以使用sendMessage。我通常包装这些调用,尝试首先使用sendMessage,如果失败,请使用transferUserInfo:

// On the iPhone
func trySendMessage(message: [String : AnyObject]) {
    if self.session != nil && self.session.paired && self.session.watchAppInstalled {
        self.session.sendMessage(message, replyHandler: nil) { (error) -> Void in
            // If the message failed to send, queue it up for future transfer
            self.session.transferUserInfo(message)
        }
    }
}


在手表上,您将需要同时实现session:DidReceiveMessage和session:didReceiveUserInfo。请注意,我不会费心检查手表是否可以到达,因为如果手表无法到达(或者手表开始可到达并且在检查之后但在传输完成之前移出了范围),那么手表仍然会发送数据从transferUserInfo返回范围。

关于ios - WatchKit上没有收到达尔文通知,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35154998/

10-12 03:07