简体   繁体   中英

Send Name and Birthday to Watch using WatchConnectivity

I'm accessing a users Contacts to send the contact Name and Birthday from the iPhone to the AppleWatch. I have access to the Contacts and can display the data on the phone, but I'm having trouble sending the info with WatchConnectivity. I'm using the Ray Wenderlich book WatchOS by Tutorials as a guide but am still having trouble.

Here is what I have on the Phone side to set up Watch Connectivity in AppDelegate.swift .

// MARK:  Watch Connectivity
extension AppDelegate: WCSessionDelegate {

func sessionDidBecomeInactive(_ session: WCSession) {
    print("WC Session did become inactive.")
}

func sessionDidDeactivate(_ session: WCSession) {
    print("WC Session did deactivate.")
    WCSession.default().activate()
}


func session(_ session: WCSession, activationDidCompleteWith activationState: WCSessionActivationState, error: Error?) {
    if let error = error {
        print("WC Session activation failed with error:" + "\(error.localizedDescription)")
        return
    }
    print("Phone activated with state:" + "\(activationState.rawValue)")
}

func setUpWatchConnectivity() {
    if WCSession.isSupported() {
        let session = WCSession.default()
        session.delegate = self
        session.activate()
        }
    }

}

And this in ViewController.swift

// MARK Watch Connectivity

extension ViewController {


func sendNameAndBirthdayToWatch() {
    if WCSession.isSupported() {
        let session = WCSession.default()
        if session.isWatchAppInstalled {
            let nameAndBirthday = ["name": nameLabel.text, "birthday": birthdayLabel.text]
            do {
                try session.updateApplicationContext(nameAndBirthday)
            } catch {
                print("Error")
            }
         }
     }
  }

}

I'm calling sendNameAndBirthdayToWatch() with a UIButton on the phone. As a prototype the phone currently displays the name and birthday on two separate labels pulled from the Contacts in the Xcode simulator so I at least know I'm getting the data.

On the watch in the ExtensionDelegate.swift I have.

// MARK: Watch Connectivity
extension ExtensionDelegate: WCSessionDelegate {

func session(_ session: WCSession, activationDidCompleteWith activationState: WCSessionActivationState, error: Error?) {
    if let error = error {
        print("Activation failed with error: \(error.localizedDescription)")
        return
    }
    print("Watch activated with activation state: \(activationState.rawValue) ")
}

func setupWatchConnectivity() {
    if WCSession.isSupported() {
        let session = WCSession.default()
        session.delegate = self
        session.activate()
    }
}

func session(_ session: WCSession, didReceiveApplicationContext applicationContext: [String : Any]) {
    if let name = applicationContext["name"] as? String, let birthday = applicationContext["birthday"] as? String {
        InterfaceController.sharedInterfaceController.updateWatchLabel(name: name, birthday: birthday)
    }
}
}

This is where I'm stuck. I'm not sure where I've gone wrong and/or how to move forward.

I'm calling updateWatchLabel() in the InterfaceController.swift on the watch, but I'm not seeing any results.

Thank you in advance for any help. I've been staring at this for a solid week and unfortunately the example project in the Wenderlich book is a bit too complicated for my understanding.

I'm using Xcode 8.2.1 and Swift 3.

In time I answered my own question.

Here is the code on the phone in ViewController.swift . The code remains the same as in my original post in AppDelegate.swift .

    func sendMessageToWatch() {
    if WCSession.isSupported() {
        let session = WCSession.default()
        if session.isWatchAppInstalled {
            do {
                let message = ["message": "A message as String"]
                try session.updateApplicationContext(message)
            } catch {
                print("Error: \(error)")
            }

        } else if session.isWatchAppInstalled == false {
            print("No watch app installed")
        }
    }
}

I am at the moment calling this function by pressing a UIButton on the phone. Then on the watch side in InterfaceController.swift for the receiving end. I basically moved the code from ExtensionDelegate.swift to InterfaceController.swift .

    // MARK: Watch Connectivity
func session(_ session: WCSession, activationDidCompleteWith activationState: WCSessionActivationState, error: Error?) {
    if let error = error {
        print("Activation failed with error: \(error.localizedDescription)")
        return
    }
    print("Watch activated with activation state: \(activationState.rawValue) ")
}


func setupWatchConnectivity() {
    if WCSession.isSupported() {
        let session  = WCSession.default()
        session.delegate = self
        session.activate()
    }
}

func session(_ session: WCSession, didReceiveApplicationContext applicationContext: [String : Any]) {
    let message = applicationContext["message"] as? String

    DispatchQueue.main.async(execute:  {
        self.label.setText(message)
    })

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM