Developer

How to use the Touch Bar API when developing for new MacBook Pro 2016

Learn how to create Touch Bar extensions for your macOS Sierra apps, and how to use the Touch Bar simulator to run the apps you build for Touch Bar.

touchbarhero.jpg
Apple, Inc.

One of the biggest announcements out of Apple's MacBook event last week was the unveiling of the new MacBook Pro keyboard, which includes a feature dubbed the Touch Bar. This OLED display at the top of the keyboard has two nifty features.

First, it contains a Touch ID sensor to the right side that serves as both the power button for the MacBook Pro and the Touch ID sensor. Second, it is a screen that runs the length of the keyboard and provides context-aware buttons, actions, and UI depending on which app is currently selected on the main Mac screen.

Developers, we'll show you how to create Touch Bar extensions for your apps, and how to use the Touch Bar simulator to run the apps you build for Touch Bar.

SEE: New MacBook Pro is an Intel/ARM hybrid, and here's why it's a big deal (TechRepublic)

Human Interface Guidelines for Touch Bar

Before you start writing apps for the Touch Bar on macOS Sierra, it's important that you read and understand Apple's Human Interface Guidelines (HIG) for Touch Bar. This guide has all of the information you need to know about the touch interaction and UI elements that the Touch Bar apps can include.

SEE: Apple MacBook Pro (13-inch, 2016) review (CNET)

Building an NSTouchBar app

Building a Touch Bar app utilizes the class known as NSTouchBar. You can implement this in your window controllers where each window can contain its own custom Touch Bar.

The window controller conforms to the NSTouchBarProvider delegate by default, so you only need to override the methods called makeTouchBar() and touchBar(_ touchBar: NSTouchBar, makeItemForIdentifier identifier: NSTouchBarItemIdentifier). The first methods returns an NSTouchBar instance that has placeholders for the items that are included on the bar (such as label, button, etc.), and the second method is where you will configure each item on the Touch Bar and return those items to the system. The following is an example of these two methods.

@available(OSX 10.12.1, *)
    override func makeTouchBar() -> NSTouchBar? {
        
        let touchBarIdenitifier = NSTouchBarCustomizationIdentifier(rawValue: "com.corybohon.TouchBarExample")
        let touchBarLabelIdentifier = NSTouchBarItemIdentifier(rawValue: "com.corybohon.TouchBarExample.label")
        
        let touchBar = NSTouchBar()
        touchBar.delegate = self
        touchBar.customizationIdentifier = touchBarIdenitifier
        touchBar.defaultItemIdentifiers = [touchBarLabelIdentifier, .fixedSpaceLarge, .otherItemsProxy]
        touchBar.customizationAllowedItemIdentifiers = [touchBarLabelIdentifier]
        
        return touchBar
    }
    
    @available(OSX 10.12.1, *)
    func touchBar(_ touchBar: NSTouchBar, makeItemForIdentifier identifier: NSTouchBarItemIdentifier) -> NSTouchBarItem? {
        
        if identifier.rawValue == "com.corybohon.TouchBarExample.label" {
            let custom = NSCustomTouchBarItem(identifier: identifier)
            custom.customizationLabel = "Label"
            
            let label = NSTextField.init(labelWithString: "Hello, World!")
            custom.view = label
            
            return custom
        }
        
        return nil
        
    }

In the above code, a Touch Bar is created that has a single label that says "Hello, World!"

The only other code needed is to conform to NSTouchBarDelegate and implement the method to handle taps on the items. This method gets called whenever the user taps a Touch Bar item.

For more information on getting up and running with Touch Bar in your macOS apps, check out the documentation for NSTouchBar.

Running an app that uses NSTouchBar

When you run an app that implements NSTouchBar, you can open the Touch Bar simulator by selecting Xcode | Window | Show Touch Bar. The Touch Bar will appear on the screen as a floating modal that appears over the top of all other windows (Figure A). You can even navigate around the system and see the Touch Bar in action, changing to match the current app that's on screen.

Figure A

touchbarfigurea.jpg

The Touch Bar as it appears when running the sample code from above. Notice the "Hello World!" label placed on the right hand side.

Touch ID on Mac

Another addition to the new MacBook Pros and the macOS available APIs is the addition of the same LocalAuthentication framework found on iOS. You can use the exact same code from your iOS apps that support Touch ID to request authentication with the user's fingerprint.

Do this in your Swift-based project by using the following code for basic LocalAuthentication fingerprint checking.

import LocalAuthentication
    
    let context = LAContext()
    let reasonString = "Touch ID Authorization"
    
    var authError: NSError? = nil
    
    if context.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: &authError) {
    
        context.evaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, localizedReason: reasonString) { (success, evaluateError) in
            // TODO: Handle success or failure here
        }
    } else {
        // TODO: Device doesn't have Touch ID, handle appropriately here
    }

The above code simply asks the user to authenticate with their fingerprint. You receive a Boolean value that determines whether the user's fingerprint check succeeded or failed.

Also see

    About Cory Bohon

    Cory Bohon is an indie developer specializing in iOS and OS X development. He runs a software company called Cocoa App and is also a developer at MartianCraft. He was introduced to technology at an early age and has been writing about his favorite te...

    Editor's Picks

    Free Newsletters, In your Inbox