Quick actions in SwiftUI
Quick actions are a powerful feature in SwiftUI that allows developers to add contextually relevant actions to their views. These actions can be triggered by user interactions, such as tapping and holding on a view, and can provide a more streamlined and efficient user experience.
Static Quick Actions
Static quick actions are predefined actions that can be added to a view without requiring any additional configuration. These actions are typically used for common tasks, such as sharing content or navigating to a specific screen.
Defining Quick Actions
We are going to add some information to the Info.plist file:
-
UIApplicationShortcutItemType– A unique identifier for the action, used later when handling the action. -
UIApplicationShortcutItemIconSymbolName– Specifies an SF Symbol for the action’s icon. -
UIApplicationShortcutItemTitle– Displays the action’s title.
<key>UIApplicationShortcutItems</key>
<array>
<dict>
<key>UIApplicationShortcutItemType</key>
<string>favoritesAction</string>
<key>UIApplicationShortcutItemIconSymbolName</key>
<string>heart</string>
<key>UIApplicationShortcutItemTitle</key>
<string>Favorites</string>
</dict>
</array>
Tip: To localize the title, you can add the value from
UIApplicationShortcutItemTitleto your localization file.
Dynamic Quick Actions
This is an example of how to update quick actions dynamically based on the app's state.
We use UIApplicationShortcutItem to create a quick action item, and then we update the quick actions based on the app's state, such as when the user adds or removes items from their favorites.
func updateQuickActionItems() {
// Check if there are any favorite items, otherwise don't return quick actions
guard !favorites.isEmpty else {
// Tell the system about the new quick actions (no actions)
UIApplication.shared.shortcutItems = []
return
}
// Create a quick action for the favorites
let favoritesAction = UIApplicationShortcutItem(
type: "favoritesAction",
localizedTitle: "Favorites",
localizedSubtitle: nil,
icon: UIApplicationShortcutIcon(systemImageName: "heart"),
userInfo: [:]
)
// Tell the system about the new quick actions
UIApplication.shared.shortcutItems = [favoritesAction]
}
Note: You need to call
updateQuickActionItems()on a convenient place, i'll suggest to call it when the favorites list is updated.
Handling Quick Actions
SwiftUI unfortunately does not provide a built-in way to handle quick actions directly. However, we can use the AppDelegate and SceneDelegate to manage quick actions.
We need to use a lot of UIKit integration to make this work. Here's how you can set it up:
-
@UIApplicationDelegateAdaptorto tell SwiftUI that we want to useAppDelegate -
AppDelegateto manage the application lifecycle -
UISceneConfigurationto configure the app's scenes -
UIWindowSceneDelegateto manage the app's windows
@main
struct MyApp: App {
// Set up delegate adaptor
@UIApplicationDelegateAdaptor(AppDelegate.self) private var appDelegate
var body: some Scene {
WindowGroup {
ContentView()
}
}
}
// Set up AppDelegate
class AppDelegate: NSObject, UIApplicationDelegate {
// Register SceneDelegate
func application(
_ application: UIApplication,
configurationForConnecting connectingSceneSession: UISceneSession,
options: UIScene.ConnectionOptions
) -> UISceneConfiguration {
let configuration = UISceneConfiguration(
name: nil,
sessionRole: connectingSceneSession.role
)
if connectingSceneSession.role == .windowApplication {
configuration.delegateClass = SceneDelegate.self
}
return configuration
}
}
// Set up SceneDelegate
class SceneDelegate: NSObject, UIWindowSceneDelegate {
// Handle quick action (fresh start)
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
if let shortcutItem = connectionOptions.shortcutItem {
handleShortcut(shortcutItem)
}
}
// Handle quick action (resuming app)
func windowScene(
_ windowScene: UIWindowScene,
performActionFor shortcutItem: UIApplicationShortcutItem,
completionHandler: @escaping (Bool) -> Void
) {
handleShortcut(shortcutItem)
completionHandler(true)
}
// Handle quick action
func handleShortcut(_ item: UIApplicationShortcutItem) {
if item.type == "favoritesAction" {
print("Show favorites")
}
}
}
Caveats
-
Quick actions do not work great with SwiftUI it requires a lot on UIKit integration.
-
You need to manage the application lifecycle and window scenes manually.
Wrap up
In this article, we explored how to implement quick actions in a SwiftUI application. We covered static quick actions defined in the app's Info.plist file, as well as dynamic quick actions that can be updated at runtime. We also discussed how to handle quick actions using the AppDelegate and SceneDelegate.
Resources:
-
https://developer.apple.com/documentation/uikit/uiapplicationshortcutitem
-
https://developer.apple.com/documentation/xcode/localizing-and-varying-text-with-a-string-catalog
-
https://developer.apple.com/documentation/swiftui/uiapplicationdelegateadaptor
-
https://developer.apple.com/documentation/uikit/uiapplicationdelegate
-
https://developer.apple.com/documentation/uikit/uisceneconfiguration
-
https://developer.apple.com/documentation/uikit/uiwindowscenedelegate
Read more
- Difference between map, flatMap, compactMap • 4 minutes reading time.
- Swipe actions in Swift • 5 minutes reading time.
- Simplifying Game Controller Integration with GameControllerKit • 5 minutes reading time.
Share
Share Bluesky Mastodon Twitter LinkedIn Facebook