如何从父 ios 应用调用 watchkit 扩展中的方法

How to call the method in watchkit extension from parent ios app

我们可以从手表套件扩展中调用父 ios 应用程序中的方法 openParentApplication:reply:

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

对于 example:In 我的应用程序,当用户在 ios 应用程序中添加事件时,watchkit 事件列表也应该刷新,因此当用户在主应用程序。

请帮忙。

谢谢。

你不能直接从 watchkit 扩展中调用方法,但你可以发送 darwin 通知(或使用 MMWormhole 库(here),并在收到它后执行适当的方法。

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

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

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) 通过在 WCSessionDelegate 委托 class.

中实现 session didReceiveMessage 方法,在 WatchKit 扩展中接收消息
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" 和消息密钥 "message from iOS app"。但在实际应用中,最好使用这些文本字符串的属性以避免拼写错误。