Sending data from iPhone to Apple Watch and vice versa using Swift 5

In this tutorial, we will learn how to send data from iPhone to Apple watch and Apple watch to iPhone using Swift 5. As we all familiar that Apple watch apps demands are keep growing these days.
We are going to achieve below.

Now let’s start coding

-Create a new project and choose watchOS and select iOS App with WatchKit App.

-Now enter your Product Name and select Notification Scene as per your uses.

Design your Storyboard

– Open your Main.storyboard and go to ViewController nib file.
– Add a UILabel and UIButton over the View.

-Create IBOutlet of UILabel with name label
-Add IBAction function to UIButton with name tapSendDataToWatch

Move to your UIViewController Class

Open your ViewController Class and make below changes
import UIKit
import WatchConnectivity//1

class ViewController: UIViewController {

    var session: WCSession?//2
    @IBOutlet weak var label: UILabel!//3
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        self.configureWatchKitSesstion()//4
    }
    
    func configureWatchKitSesstion() {
        
        if WCSession.isSupported() {//4.1
            session = WCSession.default//4.2
            session?.delegate = self//4.3
            session?.activate()//4.4
        }
    }
    //5
    @IBAction func tapSendDataToWatch(_ sender: Any) {
        
        if let validSession = self.session {//5.1
            let data: [String: Any] = ["iPhone": "Data from iPhone" as Any] // Create your Dictionay as per uses
            validSession.transferUserInfo(data)
        }
    }    
}

// WCSession delegate functions
extension ViewController: WCSessionDelegate {
    
    func sessionDidBecomeInactive(_ session: WCSession) {
    }
    
    func sessionDidDeactivate(_ session: WCSession) {
    }
    
    func session(_ session: WCSession, activationDidCompleteWith activationState: WCSessionActivationState, error: Error?) {
    }
    
    func session(_ session: WCSession, didReceiveUserInfo userInfo: [String : Any] = [:]) {
        print("received data: \(userInfo)")
        DispatchQueue.main.async { //6
            if let value = userInfo["watch"] as? String {
                self.label.text = value
            }
        }
    }
}
1. Import WatchConnectivity framework, this will help to connect the iPhone and watch
2. WCSession will help us to communicate between iOS and WatckKit
3. This is IBOutlet of UILabel
4. Calling configureWatchKitSesstion to initialize WCSession
4.1 Check that WCSession is supported or not
4.2 Initializing WCSession
4.3 Set WCSessionDelegate to session
4.4 Activate WCSession in order to transfer data
5. This is IBAction function on UIButton
5.1 Sending data to Apple watch using transferUserInfo function of WCSession
6 Receiving data when Apple watch send to iPhone

Move to Watch and Open Watch Interface.storyboard

– Open Interface.storyboard and select InterfaceController nib file.
– Add a WKInterfaceLabel and WKInterfaceButton over the InterfaceController nib file.
– Create IBOutlet of WKInterfaceLabel and add IBAction on WKInterfaceButton with name tapSendToiPhone

Move to InterfaceController Class

Open InterfaceController Class and make below changes.
import WatchKit
import Foundation
import WatchConnectivity //**1

class InterfaceController: WKInterfaceController {
    
    @IBOutlet weak var label: WKInterfaceLabel!//**2
    let session = WCSession.default//**3
    
    override func awake(withContext context: Any?) {
        super.awake(withContext: context)
        
        // Configure interface objects here.
        session.delegate = self//**4
        session.activate()//**5
    }
    
    override func willActivate() {
        // This method is called when watch view controller is about to be visible to user
        super.willActivate()
    }
    
    override func didDeactivate() {
        // This method is called when watch view controller is no longer visible
        super.didDeactivate()
    }
    
    @IBAction func tapSendToiPhone() {//**6
        let data: [String: Any] = ["watch": "data from watch" as Any] //Create your dictionary as per uses
        session.transferUserInfo(data)//**6.1
    }
}

extension InterfaceController: WCSessionDelegate {
    
    func session(_ session: WCSession, activationDidCompleteWith activationState: WCSessionActivationState, error: Error?) {
    }
    
    func session(_ session: WCSession, didReceiveUserInfo userInfo: [String : Any] = [:]) {//**7
        print("received data: \(userInfo)")
        if let value = userInfo["iPhone"] as? String {//**7.1
            self.label.setText(value)
        }        
    }
}
1. Import WatchConnectivity framework
2. Crate IBoutlet of WKInterfaceLabel which we have added over nib file above
3. Get a default object of WCSession
4. Assign WCSessionDelegate to the session object
5. Activate WCSession in order to transfer data between iOS and WatchKit
6. This is IBAction function which we have added on WKInterfaceButton
6.1 Send data to iPhone using transferUserInfo function of WCSession
7. When the iPhone send data to then watch then didReceiveUserInfo delegate function will invoke.
7.1 Get the userInfo which is sent from iPhone and set this to WKInterfaceLabel
Now run your code
Note: If you forget to activate your session then, you will get an error log “swift wcsession counterpart app not installed” message while sharing data

Read our next Article: Easiest way to dismiss keyboard UITextView

3 comments on “Sending data from iPhone to Apple Watch and vice versa using Swift 5

  1. sirgliofrei

    Greetings! Very helpful advice on this article! It is the little changes that make the biggest changes. Thanks a lot for sharing!

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *