A watchOS 2 WatchKit Notification Tutorial

From Techotopia
Revision as of 19:45, 10 May 2016 by Neil (Talk | contribs) (Text replacement - "<!-- Ezoic - BottomOfPage - bottom_of_page --> <div id="ezoic-pub-ad-placeholder-114"></div> <!-- End Ezoic - BottomOfPage - bottom_of_page -->" to "<htmlet>ezoicbottom</htmlet>")

Jump to: navigation, search
PreviousTable of ContentsNext
An Overview of Notifications in watchOS 2A watchOS 2 WatchKit Custom Notification Tutorial


Purchase the full edition of this watchOS 2 App Development Essentials book in eBook ($12.99) or Print ($27.99) format
watchOS 2 App Development Essentials Print and eBook (ePub/PDF/Kindle) editions contain 35 chapters.

Buy Print


This chapter will create an iOS project containing a WatchKit app that demonstrates the use of the iOS notification system. The example will make use of the standard WatchKit short-look and long-look notification interfaces and include the implementation of a notification action button within the long-look interface.


Contents


About the Example Project

The purpose of the project is to allow the user to trigger a notification alert after a short delay. At the point that the notification appears, the user will be given the opportunity through a notification action button on both the iPhone or Apple Watch device to repeat the notification.

Creating the Xcode Project

Start Xcode and create a new iOS project. On the template screen choose the Application option located under watchOS in the left hand panel and select iOS App with WatchKit App. Click Next, set the product name to NotifyDemoApp, enter your organization identifier and make sure that the Devices menu is set to Universal.

Before clicking Next, change the Language menu to Swift and switch all of the Include options off (the Notification Scene option is only required when working with custom notifications, a topic covered in the next chapter).

On the final screen, choose a location in which to store the project files and click on Create to proceed to the main Xcode project window.


Designing the iOS App User Interface

The user interface for the parent iOS app will consist of a single Button object. Select the Main.storyboard file and add and configure this object so that the layout matches that illustrated in Figure 33 1, making sure to position the Button in the horizontal center of the layout:


Watchkit notification ios ui2.png

Figure 33-1


Display the Resolve Auto Layout Issues menu (Figure 33 2) and select the Reset to Suggested Constraints menu option listed under All Views in View Controller to establish sensible layout constraints on the button:


Watchkit notify constraints.png

Figure 33-2


With the Main.storyboard file still loaded into Interface Builder, display the Assistant Editor and establish an action connection from the Button object to a method named buttonPress. Review the code in the ViewController.swift file and add a constant declaration set to the duration of the delay:

import UIKit

class ViewController: UIViewController {

    let timeValue = 6.0

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    @IBAction func buttonPress(sender: AnyObject) {
    }
.
.
}

Setting the Notification

A method will now be added to the ViewController.swift file to configure the notification using the time delay value with an alert title of “Reminder” and an alert body which reads “Wake Up!”. In addition to these settings, the notification will be configured to play the default alert sound and assigned a category identifier of “REMINDER_CATEGORY” (this category will need to be referenced again later in the chapter when action buttons are added to the notification). Remaining in the ViewController.swift file, implement this method as outlined in the following listing:

func setNotification() {

    let localNotification:UILocalNotification =
                    UILocalNotification()

    localNotification.alertTitle = "Reminder"

    localNotification.alertBody = "Wake Up!"

    localNotification.fireDate = NSDate(timeIntervalSinceNow:
                        timeValue)
    localNotification.soundName =
            UILocalNotificationDefaultSoundName
    localNotification.category = "REMINDER_CATEGORY"

    UIApplication.sharedApplication().scheduleLocalNotification(
                localNotification)
}

The setNotification method will need to be called each time that the user taps the Set Delay button which is configured to call the buttonPressed method. Add the call to the setNotification method within the buttonPressed method:

@IBAction func buttonPress(sender: AnyObject) {
    setNotification()
}

Adding the Notification Action

When the notification is triggered, the user is to be given the option of repeating the notification using the same delay. This will involve the addition of a notification action to the notification using the “REMINDER_CATEGORY” identifier referenced each time the notification is set. The code to configure the action will be placed within the Application Delegate class within the didFinishLaunchingWithOptions method.

Purchase the full edition of this watchOS 2 App Development Essentials book in eBook ($12.99) or Print ($27.99) format
watchOS 2 App Development Essentials Print and eBook (ePub/PDF/Kindle) editions contain 35 chapters.

Buy Print

Begin by locating and selecting the AppDelegate.swift file and modifying the didFinishLaunchingWithOptions method to create the notification action as follows:

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: 
[NSObject: AnyObject]?) -> Bool {

    let repeatAction: UIMutableUserNotificationAction = 
		UIMutableUserNotificationAction()
    repeatAction.identifier = "REPEAT_IDENTIFIER"
    repeatAction.title = "Repeat"
    repeatAction.destructive = false
    repeatAction.authenticationRequired = false
    repeatAction.activationMode = 
		UIUserNotificationActivationMode.Background

    return true
}

The above code creates a new notification action instance and configures it with an identifier string (this will be used to identify which action has been selected by the user later in the project). The action is also configured to display text which reads “Repeat” on the action button and to indicate that it is a non-destructive action (in other words it does not cause the loss of any data or information). In the event that the device is locked when the notification is triggered, the action is configured such that it is not necessary for the user to unlock the device for the action to be performed.

Finally, since the notification can be repeated without the need to display the iOS app, the activation mode is set to Background mode.

The next task is to create the notification category containing the action and register it with the notification system:

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {

    var repeatAction: UIMutableUserNotificationAction = 
	UIMutableUserNotificationAction()
    repeatAction.identifier = "REPEAT_IDENTIFIER"
    repeatAction.title = "Repeat"
    repeatAction.destructive = false
    repeatAction.authenticationRequired = false
    repeatAction.activationMode = 
	UIUserNotificationActivationMode.Background

    let notificationCategory:UIMutableUserNotificationCategory =
             UIMutableUserNotificationCategory()

    notificationCategory.identifier = "REMINDER_CATEGORY"

    notificationCategory.setActions([repeatAction],
             forContext: UIUserNotificationActionContext.Default)

    let settings = UIUserNotificationSettings(forTypes: 
		[UIUserNotificationType.Sound, 
		 UIUserNotificationType.Alert, 
		 UIUserNotificationType.Badge], 
		categories: [notificationCategory])

    application.registerUserNotificationSettings(settings)

    return true
}

Compile and run the iOS app on a physical iPhone device or simulator session, allow notification access if prompted by the operating system and tap the Set Delay button. Once the delay has been set, place the app into the background by pressing the Home button on the device (or selecting the Hardware -> Home menu option within the simulator). When the notification appears, swipe downward on the alert panel to display the action button as shown in Figure 33-3:


Watchkit ios app alert2.png

Figure 33-3


Assuming that the notification appears as expected, the next step is to handle the “Repeat” action.

Implementing the handleActionWithIdentifier Method

When a notification action button configured for background mode is tapped by the user, the handleActionWithIdentifier method of the app delegate class is called. Among the items passed to the method are a notification object from which both the action and category identifiers of the action that triggered the call can be obtained together with a completion handler to be called once the action has been handled. This method now needs to be added to the AppDelegate.swift file along with a variable in which to store a reference to the view controller instance as follows:

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?
    var viewController: ViewController?

    func application(application: UIApplication, handleActionWithIdentifier identifier: String?, forLocalNotification notification: UILocalNotification, completionHandler: () -> Void) {

        if identifier == "REPEAT_IDENTIFIER" && notification.category == "REMINDER_CATEGORY" {
            viewController = ViewController()
            viewController?.setNotification()
        }
        completionHandler()
    }
.
.
.
}

The method begins by verifying that the category and action id match the repeat action. If this is a repeat action request, an instance of the ViewController class is created and the setNotification method of the instance called to repeat the notification. The completion handler block is then called to indicate that the action has been handled.

Re-run the iOS app, set up a notification and place the app in the background. Display the action button in the notification panel when it appears and tap on the “Repeat” button. After the designated time has elapsed the notification should trigger a second time as requested.

Adding Notification Icons to the WatchKit App

The WatchKit app requires that six app icons be added to fully support notifications for the Notification Center, Short-Look and Long-Look views. For each icon category, images must be provided for both 38mm and 42mm Apple Watch models. The icons used in the example can be found in the app_icons folder of the sample code download available from the following URL:

http://www.ebookfrenzy.com/code/watchOS2BookSamples.zip

Select the Assets.xcassets entry located under NotifyDemoApp WatchKit App in the Project Navigator panel and select the AppIcon image set as outlined in Figure 33-4:


Watchkit notification image set.png

Figure 33-4


Open a Finder window and navigate to the app_icons folder. Once located, drag and drop the following icon image files to the corresponding locations in the image asset catalog:

Testing the Notification on the Apple Watch

Make sure that the NotifyDemoApp target is still selected in the Xcode toolbar and run the iOS app on a physical iPhone device with which an Apple Watch is paired or simulator session. This will launch the iOS app and install the WatchKit app.

Configure a delay, tap the Set Delay button and lock the iPhone device (the simulator can be locked using the Hardware -> Lock menu option). Pick up the Apple Watch device so that the screen activates. When the time delay has elapsed, the short look notification should appear on the screen using the designated icon. After a few seconds, the scrollable long look notification should appear including the alert title, alert body, the repeat action button and a Dismiss button:


Watchkit long look notification.png

Figure 33-5


Since the repeat action is already configured to launch the iOS app in the background and re-initiate the notification, tapping the Repeat button on the notification scene of the Apple Watch will cause the notification to repeat.

Make a swiping motion from the top of the watch display to view the Notification Center panel which should also include the notification as illustrated in Figure 33 6:


Watchkit notification center.png

Figure 33-6


Summary

This chapter has worked through the design and implementation of an example application intended to demonstrate the handling of notifications from within both a containing iOS app and the corresponding WatchKit app with a particular emphasis on the use of notification actions.


Purchase the full edition of this watchOS 2 App Development Essentials book in eBook ($12.99) or Print ($27.99) format
watchOS 2 App Development Essentials Print and eBook (ePub/PDF/Kindle) editions contain 35 chapters.

Buy Print



PreviousTable of ContentsNext
An Overview of Notifications in watchOS 2A watchOS 2 WatchKit Custom Notification Tutorial