Notify WatchKit app of an update without the watch app requesting it

前端 未结 4 1478
天涯浪人
天涯浪人 2020-12-07 16:20

I\'m aware of the capabilities of WKInterfaceController openParentApplication and handleWatchKitExtensionRequest methods for the watch app to open

4条回答
  •  北海茫月
    2020-12-07 16:48

    With WatchOS 2, you can sendMessage method like that;

    Parent App

    import WatchConnectivity then;

    Add this to didFinishLaunchingWithOptions method in AppDelegate;

    if #available(iOS 9.0, *) {
        if WCSession.isSupported() {
            let session = WCSession.defaultSession()
            session.delegate = self
            session.activateSession()
    
            if !session.paired {
                print("Apple Watch is not paired")
            }
            if !session.watchAppInstalled {
                print("WatchKit app is not installed")
            }
        } else {
            print("WatchConnectivity is not supported on this device")
        }
    } else {
         // Fallback on earlier versions
    }
    

    Then in your notification function;

    func colorChange(notification: NSNotification) {
         if #available(iOS 9.0, *) {
            if WCSession.defaultSession().reachable {
               let requestValues = ["color" : UIColor.redColor()]
               let session = WCSession.defaultSession()
    
               session.sendMessage(requestValues, replyHandler: { _ in
                        }, errorHandler: { error in
                            print("Error with sending message: \(error)")
                    })
                } else {
                    print("WCSession is not reachable to send data Watch App from iOS")
                }
         } else {
             print("Not available for iOS 9.0")
         }
     }
    

    Watch App

    Do not forget to import WatchConnectivity and add WCSessionDelegate to your InterfaceController

    override func awakeWithContext(context: AnyObject?) {
        super.awakeWithContext(context)
    
        // Create a session, set delegate and activate it
        if (WCSession.isSupported()) {
            let session = WCSession.defaultSession()
            session.delegate = self
            session.activateSession()
        } else {
            print("Watch is not supported!")
        }
    }
    
    func session(session: WCSession, didReceiveMessage message: [String : AnyObject], replyHandler: ([String : AnyObject]) -> Void) { 
        if let deviceColor = message["color"] as? UIColor {
            // do whatever you want with color
        }
    }
    

    To do this, your Watch App need to work on foreground.

提交回复
热议问题