An iOS 17 Quick Actions Tutorial

Quick actions (also called application shortcuts) appear when a long press is performed on the home screen icon of an app installed on an iOS device. The actions appear in a menu format and, when selected, call delegate methods within the corresponding app allowing the app to perform tasks before being presented to the user. Quick actions are categorized as static and dynamic. Static quick actions are stored in the Info.plist file of the app bundle, while dynamic quick actions are created within the app’s code at runtime. This chapter will create an example project to outline the steps needed to add quick actions to an iOS app.

Creating the Quick Actions Example Project

Begin by launching Xcode and creating a new project using the iOS App template with the Swift and Storyboard options selected, entering QuickActions as the product name.

Static Quick Action Keys

As with all Info.plist entries, static quick actions are stored as key-value pairs, which can be summarized as follows:

  • UIApplicationShortcutItems – This key is paired with an array containing a dictionary entry for each static quick action item.
  • UIApplicationShortcutItemIconType – The value assigned to this key designates the icon to be displayed next to the quick action title. Many icon options are available for use when creating quick actions.
  • UIApplicationShortcutItemTitle – The string assigned to this key represents the title that will appear for the action in the menu.
  • UIApplicationShortcutItemSubtitle – The string assigned to this key represents the subtitle that will appear beneath the title for the action in the menu.
  • UIApplicationShortcutItemType – The value assigned to this key will be passed to the app at launch time and used to identify the quick action selected by the user. This property can be set to any string value uniquely identifying the action within the app’s context.
  • UIApplicationShortcutItemUserInfo – The value assigned to this key takes the form of a dictionary that can be used to pass additional data through to the app when the corresponding action is selected.

Adding a Static Quick Action to the Project

In this tutorial step, the key-value pairs outlined above will be added to the Info.plist file to add a quick action to the app. While these elements could be added using the Info screen of the project target, as we have done in earlier chapters, it will be faster in this instance to display and edit the settings in XML format. To see the file in XML format, right-click on the Info entry in the Project Navigator panel and select the Open As -> Source Code menu item and add a shortcut item as follows:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
	<key>UIApplicationSceneManifest</key>
.
.					<string>Main</string>
				</dict>
			</array>
		</dict>
	</dict>
    <key>UIApplicationShortcutItems</key>
    <array>
        <dict>
            <key>UIApplicationShortcutItemIconType</key>
            <string>UIApplicationShortcutIconTypePlay</string>
            <key>UIApplicationShortcutItemTitle</key>
            <string>Play</string>
            <key>UIApplicationShortcutItemSubtitle</key>
            <string>Start playback</string>
            <key>UIApplicationShortcutItemType</key>
            <string>PlayMusic</string>
            <key>UIApplicationShortcutItemUserInfo</key>
            <dict>
                <key>firstShortcutKey1</key>
                <string>firstShortcutKeyValue1</string>
            </dict>
        </dict>
    </array>
</dict>
</plist>Code language: HTML, XML (xml)

Switch back to Property Editor mode by right-clicking on the Info.plist file once more, this time selecting the Open As -> Property List menu option. Next, unfold the Home Screen Shortcut Items entries and verify they match Figure 86-1:

 

You are reading a sample chapter from Building iOS 17 Apps using Xcode Storyboards.

Buy the full book now in eBook or Print format.

The full book contains 96 chapters and 760 pages of in-depth information.

Learn more.

Preview  Buy eBook  Buy Print

 

Figure 86-1

Adding a Dynamic Quick Action

The next step is to add some code to the app delegate class to add a dynamic quick action to the app. In code, quick actions are represented by the UIApplicationShortcutItem class on which the same properties must be set as those defined for a static quick action. Since instances of the UIApplicationShortcutItem class are immutable, new quick action items are created using the UIMutableApplicationShortcutItem class. Once quick action items have been created and configured, they are added to the app by placing them in an array and assigning that array to the shortcutItems property of the app context.

To add dynamic quick actions to the app, select the SceneDelegate.swift file and modify the sceneWillResignActive method to create and add the dynamic actions. By placing the code in this method, we ensure that the shortcuts are added when the app is placed in the background:

func sceneWillResignActive(_ scene: UIScene) {
    let application = UIApplication.shared
    
    let shortcut2 = UIMutableApplicationShortcutItem(type: "SearchMusic",
            localizedTitle: "Search",
            localizedSubtitle: "Find a track to play",
            icon: UIApplicationShortcutIcon(type: .search),
            userInfo: nil
    )

    let shortcut3 = UIMutableApplicationShortcutItem(type: "AddMusic",
            localizedTitle: "Add Track",
            localizedSubtitle: "Add track to playlist",
            icon: UIApplicationShortcutIcon(type: .add),
            userInfo: nil
    )

    application.shortcutItems = [shortcut2, shortcut3]
}Code language: Swift (swift)

Compile and run the app on a device or simulator and press the device home button to place the app in the background. Next, locate the icon for the app on the device home screen and perform a long press on it, at which point the quick action menu should appear as shown in Figure 86-2:

Figure 86-2

Adding, Removing, and Changing Dynamic Quick Actions

Once a dynamic quick action has been added, it will remain in effect until the app is deleted or the code takes steps to remove or modify it. All currently configured dynamic quick action items can be removed simply by assigning an empty array to the app’s shortCutItems property. For example:

application.shortcutItems = []Code language: Swift (swift)

It is also possible to access the array of current dynamic quick action items and modify one or more before reassigning the array. The following code, for example, gets the current array of dynamic action items and replaces the first item in the array with a different action:

 

You are reading a sample chapter from Building iOS 17 Apps using Xcode Storyboards.

Buy the full book now in eBook or Print format.

The full book contains 96 chapters and 760 pages of in-depth information.

Learn more.

Preview  Buy eBook  Buy Print

 

var shortcuts = application.shortcutItems

let shortcut4 = UIMutableApplicationShortcutItem(type: "PauseMusic",
            localizedTitle: "Pause",
            localizedSubtitle: "Pause playback",
            icon: UIApplicationShortcutIcon(type: .pause),
            userInfo: nil
        )

shortcuts![0] = shortcut4
application.shortcutItems = shortcutsCode language: Swift (swift)

Responding to a Quick Action Selection

When a quick action item is selected from the menu, the performActionFor shortcutItem: method of the scene delegate is called and passed the UIApplicationShortcutItem object for the selected action. The object’s properties can then be accessed to determine the selected action and react accordingly. As the next step in this tutorial, add the following implementation of the performActionFor shortcutItem: method to the SceneDelegate.swift file:

func windowScene(_ windowScene: UIWindowScene,
                 performActionFor shortcutItem: UIApplicationShortcutItem,
                 completionHandler: @escaping (Bool) -> Void) {
    
    switch shortcutItem.type {
        case "PlayMusic" :
            notifyUser(message: shortcutItem.localizedTitle)
        case "PauseMusic" :
            notifyUser(message: shortcutItem.localizedTitle)
        case "SearchMusic" :
            notifyUser(message: shortcutItem.localizedTitle)
        case "AddMusic" :
            notifyUser(message: shortcutItem.localizedTitle)
        default:
            break
    }
    completionHandler(true)
}Code language: Swift (swift)

The method performs a switch operation on the UIApplicationShortcutItemType property of the action item object and calls a method named notifyUser, passing through the title from the action item before calling the completion handler. All that remains is to implement the notifyUser method in the AppDelegate.swift file, which displays an alert dialog containing the title string:

func notifyUser(message: String) {

    let alertController = UIAlertController(title: "Quick Action",
                    message: message,
                    preferredStyle: .alert)
    let okAction = UIAlertAction(title: "OK",
                    style: .default,
                    handler: nil)

    alertController.addAction(okAction)

    window?.rootViewController?.present(alertController,
            animated: true, completion: nil)
}Code language: Swift (swift)

Testing the Quick Action App

Compile and rerun the app, press the device home screen to place it in the background, and test the quick action items. When each is selected, the app should launch and display an appropriately configured alert dialog:

Figure 86-3

Summary

Quick actions allow users to make choices before launching an app by pressing the app’s home screen icon and selecting from a menu. Once selected, the action item is passed to the app delegate via the performActionFor shortcutItem: method, where it can be identified and handled.

Quick action items can be static or dynamic. Static action items are declared in the Info.plist file and cannot be changed at runtime. Dynamic action items are configured in code using the UIMutableApplicationShortcutItem class and assigned in array format to the app’s shortcutItems property. Unlike static action items, dynamic items can be added, removed, and replaced during runtime.

 

You are reading a sample chapter from Building iOS 17 Apps using Xcode Storyboards.

Buy the full book now in eBook or Print format.

The full book contains 96 chapters and 760 pages of in-depth information.

Learn more.

Preview  Buy eBook  Buy Print

 


Categories