在Swift应用程序中,为什么WatchKit和NSNotificationCenter只以单向工作?

时间:2015-03-25 09:27:12

标签: swift nsnotificationcenter watchkit

当从WatchKit Extension InterfaceController发送NSNotificationCenter通知时,我们可以从ViewController获取它,但是当从ViewController发送通知时,我们无法从WatchKit Extension InterfaceController获取它。

这是工作通知;

我们在ViewController中将通知设置为

   override func viewDidLoad() {
    super.viewDidLoad()

  NSNotificationCenter.defaultCenter().addObserver(self, selector:    "action_notification_WatchButton:", name: "notification_WatchButton", object: nil) 

 }

我们在ViewController中收到

的通知
 func action_notification_WatchButton(notification:NSNotification) {

    println("watch button touched")        
}

我们从WatchKit Extension InterfaceController发送通知

     @IBAction func buttonWatch() {

     NSNotificationCenter.defaultCenter().postNotificationName("notification_WatchButton", object:nil, userInfo:nil)

}

这样在手表和手机应用程序运行时都能正常工作。当我们触摸按钮手表

println(“触摸按钮”)

打印文字。很好。

但是当我们在

中设置通知时
override func willActivate() {

  NSNotificationCenter.defaultCenter().addObserver(self, selector:    "action_notification_WatchButton:", name: "notification_WatchButton", object: nil)  

 }

我们放

  func action_notification_WatchButton(notification:NSNotification) {

    println("phone button touched")        
}

在WatchKit Extension的InterfaceController下,我们使用

@IBAction func buttonPhone() {
     NSNotificationCenter.defaultCenter().postNotificationName("notification_WatchButton", object:nil, userInfo:nil)
  }

在ViewController按钮功能内部,按下电话上的按钮没有应答。

1 个答案:

答案 0 :(得分:3)

您应该阅读Darwin notificationsMMWormhole。这将解决您的通知问题。