Apple Watch App – How to go about it!

With the announcement of Apple Watch, there has been a buzz for development of apps for it. In this tutorial we will make a Watch App using Swift and add some nice cool features in it. So lets get started!

You can start either by making a fresh new project or adding a new extension to an earlier developed iOS project. In both cases the watch app will work just perfect.

You need to have Xcode 6.2 beta or above to develop Apple watch apps.

Your Apple watch app is not the substitute of your iOS app but it is complimentary. You need your iOS device to be near the watch as it uses the Bluetooth LE to communicate with each other. If your iOS device is locked and you launch your third party watch kit apps it will show a message “Unlock to activate”.

Let us first understand how the watch app works :

When the app is launched on the watch, the companion iOS extension is automatically launched. They both work in synergy, with the watch app showing content to the watch and responding to interactions, while iOS extension is doing everything else. Actually, no application code is executed on the watch : all processing is delegated to the iOS extension.

image 1

In case you are starting with an existing project skip the step 1.

 

Step 1. In Xcode : Choose File -> New -> Project -> Single View Application. Name the project and choose Swift as the language. Fill out the other details and click “Next” and save it. You would now see that xcode has provided with the initial classes.To make an apple watch app we need to add “Watch Kit extension” to the project.

 

Step 2. In project Navigator click on your project name , click on (+) button on bottom side to add a new extension to the project. Choose Apple watch -> WatchKit App. Click next and you will see other settings which the xcode asks you.

image 2

  1. Choose language as Swift.
  2. You will see ‘Include Notification Scene’ and ‘Include Glance Scene’ are provided with checkboxes against them.

 

Just to brief up what Notification and Glance scenes are in Watch App are:

  1. Notification Scene – Notifications on Apple Watch facilitate quick, lightweight interaction in two parts: the Short Look and the Long Look. A Short Look appears when a local or remote notification needs to be presented to the user. A Short Look provides a discrete, minimal amount of information. If the wearer lowers his or her wrist, the Short Look disappears. A Long Look appears when the wearer’s wrist remains raised or the user taps the short look interface. It provides more detailed information and more functionality and it must be actively dismissed by the wearer.
  2. Glance Scene – Glances are read-only, single page, and non scrollable views, used for showing a snapshot of a timely and relevant app-specific data. No user interaction is allowed, except for the tap event. Tap on the glance will simply launch the app, optionally providing a context to let the app display a specific interface controller.

 

So we will select both the checkboxes to include glances and notification scene in our app.

Click on “Finish” and you will see 2 targets have been added in your project – Watch Kit Extension and Watch kit App. Watch Kit Extension runs over your iphone and provides all the computations while the Watch Kit App just displays the data manipulated by the extension.

Going in the Watch Kit App Folder in Xcode, this bundle is static, meaning that adding or changing any of the resources, views, images etc. is not possible at runtime.While the Watch Kit Extension Folder contains the classes one each for the Glance, Notification and the Root view controller of the app.

Lets have a look at watch app looks in simulator: But before that choose your simulator and go to Hardware -> External Displays. You will see 2 options : Apple Watch 38 mm and Apple Watch 42 mm. Choose any. Now select Watch Kit App from the scheme and run. You must be wondering as to what will be seen on the simulator but it turns out that it just shows the time as we haven’t added code in it.

 So lets dive in making the watch App work.

 

Step 3. If you started with an existing project then you want to display some information on the watch app which interests the user. As the watch app is all about extending the ios app functionality on your wrist. Here we will make a basic functionality in which we will display the table and the selected rows value will be updated on the watch.

 We start with the iOS App and add UITableView in the storyboard and connect it using the Assistant Editor to the class. Connect the delegate and datasource to the view controller.

As we started with a fresh project and after set up, the viewcontroller should look like the code given below. It contains just the basic functions to populate the table and get row selection in it. We will have to add the code with which we tell the watch App the text of the row selected.

 Use the following code to make UITableView work in ViewController class.


import UIKit

class ViewController: UIViewController , UITableViewDataSource, UITableViewDelegate{

@IBOutlet weak var table: UITableView!
let dataArray = ["Obejct 1", "Object 2", "Object 3","Object 4"];
let cellIdentifier = "cellIdentifier"

override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}

func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dataArray.count
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) ->
UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as! UITableViewCell
cell.textLabel?.text = dataArray[indexPath.row];
return cell;
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
self.updateAppGroupContainer(dataArray[indexPath.row])
}

}

 

There are various ways of communication between the iOS and watch App:

  1. Writing data in shared container by enabling the App groups in project.This further can be of two types depending on requirement. NSUserDefaults, Files or Coredata can be shared between the app and its extension.
  2. Watch App can initiate communication by using openParentApplication(userInfo:reply:) of WKInterfaceController which will call application(_:handleWatchKitExtensionRequest:reply:) in iOS app delegate.

Below code describes the use of NSUserDefaults for sharing data.To enable App Groups in project, go to targets section and choose the Watch Kit Extension/ Capabilities/App Groups. Switch on the app groups and click on the add button and add the name of a Container. As you see in code, i have named my container “group.com.WatchDemoTutorial”. The Group Identifier should start with “group.” otherwise Xcode generates an error. Similarly follow the same steps for the project in Target section. You will see that the Group Identifier will already be there, just check mark it to include in the project.

Use the following code to create / update the NSUserDefaults in the Shared Container.

func updateAppGroupContainer(data : NSString)
    {
        let defaults = NSUserDefaults(suiteName: "group.com.WatchDemoTutorial")
        let dict = ["rowSelected":data]
        defaults?.setObject(dict, forKey: "currentSelection")
        defaults?.synchronize()
    }

 Step 4. We will now start working on the watchkit app and retrieve the data saved in the container. For this we now jump to the Watchkit App folder in project and select  the storyboard so that we can design our UI.

Drag Drop a Label to the Interface Controller Scene and write a static text : “Row Selected”.Drag another label in which we will update the value stored in container and connect it through an outlet.

Next we go to “InterfaceController.swift”. You will see the default methods provided by Xcode. We need to retrieve the value stored in container. “UpdateWatchKitApp” function looks for the changes in the container and updates the label.

Use the following code in InterfaceController of the Watch Kit Extension to update the watch app of the shared container.

import WatchKit
import Foundation

class InterfaceController: WKInterfaceController {

@IBOutlet weak var updateLabel: WKInterfaceLabel!
    override func awakeWithContext(context: AnyObject?) {
        super.awakeWithContext(context)
        
        // Configure interface objects here.
    }

override func willActivate() {
        // This method is called when watch view controller is about to be visible to user
        super.willActivate()
      NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("updateWatchKitApp"), userInfo: nil, repeats: true)
        self.updateWatchKitApp()
    }

override func didDeactivate() {
        // This method is called when watch view controller is no longer visible
        super.didDeactivate()
    }
func updateWatchKitApp()
        {
            let userDefaults = NSUserDefaults(suiteName:"group.com.WatchDemoTutorial")
            userDefaults!.synchronize()
            if var updatedDictionary : NSDictionary =  userDefaults!.objectForKey("currentSelection") as? NSDictionary
{
            var text : NSString = (updatedDictionary.objectForKey("rowSelected") as? NSString)!
          self.updateLabel.setText(text as String)
            }
}
}

 

Finally we have some code up there to see the results. First run the Project, select some row in you are creating a fresh project or perform those steps which lead to saving of data in container. Stop the app after that.

Next run the Watch Kit Extension, you will see the value stored in container is displayed as text on label. If you are using any other structure of dictionary while storing, use the same while retrieving. Now while the extension is running on the watch simulator, launch the app on iOS simulator by tapping on it. Now, if you will select some other row, the corresponding value will be updated on watch simulator.Upto this point we learnt how to communicate with the iOS app and display the data on watch app. The watch App’s storyboard can be customised more to include more WKInterfaceControllers.

In the starting, we included a glance scene and an notification scene but we didn’t code anything in it. So, now we will have a look at our glance scene.

 

Step 5. GLANCE SCENE- Glances are used to show the important information which you want to show to the customer. User can have a look at the glances from each app when he slides his finger from bottom to top in the same way as we open Control center in iPhone.

Lets create a glance which displays the information which is saved on the container. When a user taps on the Glance, he is directed in the watch app.

Open the StoryBoard of the WatchKit App and go to the GlanceInterfaceController. You will see that there are 2 groups in it. We can use the upper group to display the App name and lower one to display information. So lets drag drop one label in each group. Add static text to upper label and connect outlet to the second one.

Referring to the code above, the function “updateWatchKitApp()” is used to retrieve the contents in the container. With the same technique we can get the value stored and display it in it the label. After making these changes and running the Glance scheme  you will the the App name and the value stored on the glance and tapping on it will take you to the app.

 

Step 6. NOTIFICATION GLANCE – Notifications where local or remote are displayed using notification scene. It has a short and long look. Long look notification scene is customizable unlike the short look. In your project, you will find “PushNotificationPayload.apns” file. This file is a sample of how the notification will look. The code for this will be written in NotificationController.swift. Depending on the requirement of the project, local or remote or both notifications can be responded to.

Open storyboard of Watch App and click on Static Notification interface controller – i refers to the short look notification while Notification Controller scene depicts the Long Look notification. The short look scene can be changed through the “PushNotificationPayload.apns” file. The array corresponding to the key “WatchKit Simulator Actions” defines the number of buttons and the actions related to them.On clicking of any button the control is delegated to the InterfaceController where the delegate method corresponding to the local or remote notification can be used to steer the flow of the app. Similarly the alert title and alert body can be configured from this file.

 

Opening NotificationController.swift we can use

  1. override func didReceiveRemoteNotification(remoteNotification: [NSObject : AnyObject], withCompletion completionHandler: ((WKUserNotificationInterfaceType) -> Void))
  2. override func didReceiveLocalNotification(localNotification: UILocalNotification, withCompletion completionHandler: ((WKUserNotificationInterfaceType) -> Void))

 

Using the following functions in InterfaceController.swift:

  1. handleActionWithIdentifier(identifier: forRemoteNotification remoteNotification:) for handling remote notifications
  2. handleActionWithIdentifier(identifier: forLocalNotification localNotification:) for handling local notifications

 

So if you don’t change your  “PushNotificationPayload.apns”  file and select the notification scheme and run, you will see the short look of the notification first appear which is configured as the payload file. Clicking on any button performs the action assigned to it and takes the user to the app. Use the notification identifier to identify the source of the action. Using this identifier the flow of the app can be altered i.e. some different WKInterfaceController can be displayed.

 

One should note that in Watchkit App you cannot add WKIntefaceObjects at runtime. They have to be configured in your storyboard. You can show or hide them at runtime. Hiding an element frees the space occupied by it and shifts the rest of the objects to cover its space.

 

So, with this we finish the setup of basic watch app with Notification and Glance scene. Also we looked on how to set up communication between the iOS and watch app.

Leave a Reply

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


eight × 2 =

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>