Home Screen Quick Actions in SwiftUI

This tutorial is all about Quick Actions in SwiftUI. We all know what quick actions are, but we don’t know that those actions are known as Quick Actions in iOS. To make it clear let me explain it:

On the home screen in iOS, we can tap and hold on to the app icon to see the available options provided by the app to click directly from the home screen. These actions are known as Quick actions.

So, I am assuming that people are gonna find this tutorial helpful if they are looking for how to create options for tap and hold app icon in SwiftUI (iOS obviously).

We can do this in two ways, like when the app will be active and when the app will be in the background or inactive.

As the quick actions options will appear on the home screen, I will be showing you how to show those quick actions when the app is inactive or in the background. (It is a better approach in my opinion)

You can check my previous tutorial: Check if SwiftUI app is running in background, as it will help you. (You can skip if you already know how to do that)

Create Options for Quick Actions

Take a look the below code:

import SwiftUI

@main
struct codespeedyApp: App {
    @Environment(\.scenePhase) var state
    
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
        .onChange(of: state, initial: true){ initial, myValue in
            switch myValue {
            case.inactive:
                print("I am inactive")
                
            case.active:
                print("I am active")
            
            case.background:
                print("I am in background")
                myNewFunction()
            @unknown default: print("Default")
            }
        }
    }
    func myNewFunction(){
        UIApplication.shared.shortcutItems = [
            UIApplicationShortcutItem(
                type: "First action",
                localizedTitle: "Title 1",
                localizedSubtitle: "String",
                icon:UIApplicationShortcutIcon(systemImageName: "star")
            )
        ]
        
    }
}

Output: (On tapping and holding the app icon on home screen)

Quick Actions iOS using SwiftUI

As you can see, there is one option created by me (Title 1). Also added a subtitle.

Do not worry if the above code is looking a little messy for you. I am going to tell you each and every line of code that you should know to perform Quick Actions in your application.

Explanation of the above code snippet:

@Environment(\.scenePhase) var state is used to check whether the app is in the background or not.

Created myNewFunction() on line number 26 and called the function when the app is in the background. (Take a look at line number 21)

But there might be a question that arises in your mind: what will happen if I close the application completely (removing from recent apps)?

The quick actions should not work at that time right?

But no this is not gonna happen, if you even close the app, the app status will be in the background here so it will not cause any issue with your quick actions.

That’s why I have printed that active status inside every switch case to observe what’s going on.

Now this is the main part where I have created a Quick Actions Item.

func myNewFunction(){
    UIApplication.shared.shortcutItems = [
        UIApplicationShortcutItem(
            type: "First action",
            localizedTitle: "Title 1",
            localizedSubtitle: "Subtitle 1",
            icon:UIApplicationShortcutIcon(systemImageName: "star")
        )
    ]
    
}
  • type:  this key will hold only string-type value in it.
    Here, the type key is used to mark every Quick Actions item uniquely. So you should not use the same name more than once for type.
    We, the developers generally give type value like bundle identifier or package identifier format. Just like this: com.codespeedy.firstAction.
    But, it’s not necessary to follow that. It will work either way. The thing is that it must be a string.
  • localizedTitle:It also holds only string value.
    Whatever string you will write here, will be shown as the main title of your Quick Actions’s item. You can check from the given output earlier.
  • localizedSubtitle:It also can contain only string in it. Yes, it’s a subtitle and will be shown just below the title in a smaller font. We can use this to describe the function of that button for the user’s help.
  • icon:It can take image input as you can see. You can use SF symbols as icons in Quick Actions. If you wish you can also use your custom image. (Don’t wanna drag this tutorial that long right now)

Till now I have shown only 4 key’s of UIApplicationShortcutItem and these are the mandatory parameters only.

You can also add userInfo: which is optional.

If you wish to add more options or Quick Actions Buttons, you can add more UIApplicationShortcutItem. Make sure you use comma to separate those.

For example I am adding one more button:

func myNewFunction(){
    UIApplication.shared.shortcutItems = [
        UIApplicationShortcutItem(
            type: "First action",
            localizedTitle: "Title 1",
            localizedSubtitle: "Subtitle 1",
            icon:UIApplicationShortcutIcon(systemImageName: "star")
        ),
        UIApplicationShortcutItem(
            type: "Second action",
            localizedTitle: "Title 2",
            localizedSubtitle: "Subtitle 2",
            icon:UIApplicationShortcutIcon(systemImageName: "moon")
        )
    ]
    
}

Output will be like this:

Home Screen Quick Actions in SwiftUI

Add actions to our Quick Actions buttons in SwiftUI (iOS)

Till now, I have only show you how to add those quick actions buttons to your app. But what’s the point of having no functionality.

Now, I am going to show you how to perfrom or run any function or code when tapping on those Quick Actions buttons.

I will do this:

  • If you tap on “Title 1” from the home screen, it will open the app and in console of your Xcode debug, it will print “Title 1”.
  • If you tap on “Title 2” from the home screen, it will open the app and in console of your Xcode debug, it will print “Title 2”.

We need to add this below line

@UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate

And then create AppDelegate class.

Let’s check the full code:

import SwiftUI

@main
struct codespeedyApp: App {
    @Environment(\.scenePhase) var state
    @UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
    
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
        .onChange(of: state, initial: true){ initial, myValue in
            switch myValue {
            case.inactive:
                print("I am inactive")
                
            case.active:
                print("I am active")
            
            case.background:
                print("I am in background")
                myNewFunction()
            @unknown default: print("Default")
            }
        }
    }
    func myNewFunction(){
        UIApplication.shared.shortcutItems = [
            UIApplicationShortcutItem(
                type: "First action",
                localizedTitle: "Title 1",
                localizedSubtitle: "Subtitle 1",
                icon:UIApplicationShortcutIcon(systemImageName: "star")
            ),
            UIApplicationShortcutItem(
                type: "Second action",
                localizedTitle: "Title 2",
                localizedSubtitle: "Subtitle 2",
                icon:UIApplicationShortcutIcon(systemImageName: "moon")
            )
        ]
        
    }
}
class AppDelegate: NSObject, UIApplicationDelegate {
    func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration{
        let sceneConfig = UISceneConfiguration(name: "Here is my action", sessionRole: connectingSceneSession.role)
        sceneConfig.delegateClass = CustomSceneDelegate.self
        return sceneConfig
    }
}
class CustomSceneDelegate: UIResponder, UIWindowSceneDelegate {
    func windowScene(_ windowScene: UIWindowScene, performActionFor shortcutItem: UIApplicationShortcutItem, completionHandler: @escaping (Bool) -> Void) {
        print(shortcutItem.localizedTitle as Any)
    }
}

Run this on your machine and check your Xcode console while tapping the Quick Actions.

Output:

Quick Actions iOS SwiftUI Output

Leave a Reply

Your email address will not be published. Required fields are marked *