BLACK FRIDAY: Save 50% on all my Swift books and bundles! >>

Handling voice input in SwiftUI

Paul Hudson    @twostraws   

Once you've made sure your app works well with Voiceover, a great next step is to make sure it handles voice input too – that you work well with Apple's Voice Control technology, which lets users control your app by speaking to it.

Voice Input lets users activate controls through names or numbers, with the names being generated automatically based on what you present. Here's a trivial example:

Button("Tap Me") {
    print("Button tapped")
}

Because that has "Tap Me" right there on the screen, it can be activated by saying "Press Tap Me". That's neat, but things are often more complicated.

For example, lets say you had buttons with the names of various presidents, like this:

Button("John Fitzgerald Kennedy") {
    print("Button tapped")
}

That will work great as "Tap John Fitzgerald Kennedy", but wouldn't it be great to also recognize "Tap Kennedy" or perhaps even "Tap JFK"? How about recognizing all three?

This is where SwiftUI needs a little extra help from us using the accessibilityInputLabels() modifier. This accepts an array of strings that can be attached to our button, so the user can trigger it in a variety of ways. So, to trigger the button with three different phrases we'd use this:

Button("John Fitzgerald Kennedy") {
    print("Button tapped")
}
.accessibilityInputLabels(["John Fitzgerald Kennedy", "Kennedy", "JFK"])

The goal is to help the user activate your controls using whatever seems natural to them – you can provide as many strings as you want, and iOS will listen for all of them.

Save 50% in my WWDC sale.

SAVE 50% All our books and bundles are half price for Black Friday, so you can take your Swift knowledge further without spending big! Get the Swift Power Pack to build your iOS career faster, get the Swift Platform Pack to builds apps for macOS, watchOS, and beyond, or get the Swift Plus Pack to learn advanced design patterns, testing skills, and more.

Save 50% on all our books and bundles!

BUY OUR BOOKS
Buy Pro Swift Buy Pro SwiftUI Buy Swift Design Patterns Buy Testing Swift Buy Hacking with iOS Buy Swift Coding Challenges Buy Swift on Sundays Volume One Buy Server-Side Swift Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Advanced iOS Volume Three Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with macOS Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Beyond Code

Was this page useful? Let us know!

Average rating: 5.0/5

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.