2016-02-02 49 views
0

我想從我的iPhone發送通知到手錶設備使用 CFNotificationCenterAddObserver在手錶上和CFNotificationCenterPostNotification。(我不是在Xcode模擬器上測試)。WatchKit達爾文通知沒有收到的手錶

這是我在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); 
    }); 
} 

這是我如何使用它在蘋果手錶擴展應用:

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

您不能使用達爾文通知中心向watchos2發送消息,使用已使用WatchConnectivity框架 – dan

+0

將消息從手錶發送到iPhone,但是我怎樣才能以其他方式使用它? –

回答

1

您應該使用WatchConnectivity從發送消息蘋果手錶的iPhone。

手錶和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) 
     } 
    } 
} 

在手錶,你將需要實現兩個會議:DidReceiveMessage和會話:didReceiveUserInfo。請注意,我不打擾檢查手錶是否可到達,因爲如果它不可用(或者它在檢查後但轉移完成之前開始可到達並移出範圍),那麼數據仍然會在發送時發送返回從transferUserInfo範圍。

1

這是在watchOS 2上?正如其他人所建議的,您需要使用WatchConnectivity。達爾文通知將無法工作,因爲watchOS 2過程不再像在watchOS 1中那樣位於手機上。此外,WatchConnectivity更方便。