6

我们可以从 watch kit 扩展调用 openParentApplication:reply:父 ios 应用程序中的方法。

但是有什么方法可以从父 ios 应用程序调用 watchkit 扩展中的方法吗?

例如:在我的应用程序中,当用户在 ios 应用程序中添加事件时,watchkit 事件列表也应该刷新,因此当用户在主应用程序中添加新事件时,我需要在 watchkit 扩展中调用刷新方法。

请帮忙。

谢谢。

4

2 回答 2

4

您不能直接从 watchkit 扩展调用方法,但您可以发送 darwin 通知(或使用MMWormhole库(此处),并在收到后执行正确的方法。

于 2015-01-09T15:16:12.883 回答
1

您可以使用内置的WatchConnectivity框架将消息从 iOS 应用程序发送到配对的 Apple Watch。

1) 首先,在iOS 应用和 WatchKit 扩展中激活手表连接会话。在 iOS 端,它可以在application didFinishLaunchingWithOptions应用程序委托中完成。在手表方面,您可以在applicationDidFinishLaunchingWatchKit 扩展委托的方法中运行此代码。

if WCSession.isSupported() {
  let session = WCSession.defaultSession()
  session.delegate = self
  session.activateSession()
}

2) 现在从您的 iOS 应用程序发送消息。

let session = WCSession.defaultSession()

session.sendMessage(["message from iOS app":""], replyHandler: { reply in
  // Handle reply from watch (optional)      
}, errorHandler: nil)

3) 通过在您的委托类中实现该session didReceiveMessage方法,在您的 WatchKit 扩展中接收消息。WCSessionDelegate

func session(session: WCSession, didReceiveMessage message: [String : AnyObject], replyHandler: ([String : AnyObject]) -> Void) {
  if let message = message["message from iOS app"] { 
    NSNotificationCenter.defaultCenter().postNotificationName("myapp.reload", object: self, userInfo: ["data": message])
  }
}

在收到来自 iOS 的消息后,我们将发送带有postNotificationName方法的通知。

4) 在需要更新的 InterfaceController 中订阅此通知(或您希望接收此更新通知的任何其他地方)。

override func awakeWithContext(context: AnyObject?) {
  super.awakeWithContext(context)

  NSNotificationCenter.defaultCenter().addObserver(self, selector: "didReceiveReloadNotification:", name: "myapp.reload", object: nil)
}

deinit {
  NSNotificationCenter.defaultCenter().removeObserver(self,
  name: "myapp.reload", object: nil)
} 

5) 最后,实现通知处理程序方法。您可以在此处更新 UI。

func didReceiveReloadNotification(notification: NSNotification) {
  let userInfo = notification.userInfo as? [String: String]
  if let userInfo = userInfo, data = userInfo["data"] {
    // Update UI
  }
}

注意:为了便于阅读,我使用内联文本字符串作为通知名称“myapp.reload”和消息键“来自 iOS 应用程序的消息”。但在实际应用程序中,最好使用这些文本字符串的属性以避免拼写错误。

于 2015-09-20T12:12:51.973 回答