【问题标题】:How to call the method in watchkit extension from parent ios app如何从父 ios 应用程序调用 watchkit 扩展中的方法
【发布时间】:2015-03-07 21:26:01
【问题描述】:

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

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

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

请帮忙。

谢谢。

【问题讨论】:

    标签: ios objective-c swift watchkit apple-watch


    【解决方案1】:

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

    【讨论】:

    • 很好的答案!不过,我想补充一点,这没有记录为受支持。这可能会在未来被阻止,或者当他们开始接受 watchkit 应用程序时可能无法通过苹果认证。不过,目前它的效果非常好!
    【解决方案2】:

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

    1) 首先,在 iOS 应用和 WatchKit 扩展中激活手表连接会话。在 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 委托类中实现 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”和消息键“来自 iOS 应用程序的消息”。但在实际应用中,最好为这些文本字符串使用属性以避免拼写错误。

    【讨论】:

      猜你喜欢
      • 2015-08-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-19
      • 1970-01-01
      相关资源
      最近更新 更多