Home > Articles > Operating Systems, Server > MAC OS X/Other

  • Print
  • + Share This
Like this article? We recommend

Coding the Apple Watch App

Now that the iOS app is done, you can focus on the Apple Watch app. To keep things simple, we will simply display the country that the user has selected in the iOS app. This will prove that the country has been saved correctly in the iOS app and is accessible on the watch app.

  1. Select the Interface.storyboard file and add a Label control to the Interface Controller (see Figure 8). Set the Lines attributes of the Label control to 0.

    Figure 8

    Figure 8 Populating the Interface Controller with a Label view.

  2. Create an outlet for the Label control. This will create the following statements in bold in the InterfaceController.swift file:

    import WatchKit
    import Foundation
    
    class InterfaceController: WKInterfaceController {
    
        @IBOutlet weak var label: WKInterfaceLabel!
        override func awakeWithContext(context: AnyObject?) {
            super.awakeWithContext(context)
    
            // Configure interface objects here.
       }

    Add the following statements in bold to the InterfaceController.swift file:

    import WatchKit
    import Foundation
    
    class InterfaceController: WKInterfaceController {
    
        @IBOutlet weak var label: WKInterfaceLabel!
    
        //---replace "group.net.learn2develop.articles.sharingdata" with
        // the string that you have created earlier---
        var defaults = NSUserDefaults(
            suiteName: "group.net.learn2develop.articles.sharingdata")
    
        //---read a value from the setting, given a key---
        func readSettingValue(key:String) -> String? {
            return defaults?.objectForKey(key) as? String
        }
    
        override func awakeWithContext(context: AnyObject?) {
            super.awakeWithContext(context)
    
            // Configure interface objects here.
            if let countrySelected = readSettingValue("country") {
    
                self.label.setText(countrySelected)
            }
        }
  3. Select the SharingData WatchKit App scheme at the top of Xcode and run the application on the iPhone Simulator. You should now see the country name displayed on the Apple Watch Simulator. The country name should be the same as that previously selected on the iPhone Simulator (see Figure 9).
    Figure 9

    Figure 9 Testing the application on the iPhone and Apple Watch Simulators.

  • + Share This
  • 🔖 Save To Your Account