3D Touch Quick Actions Tutorial

published in iOS Development, Tutorials
by Szymon Wereszczyński

Did you know that the iPhone is able to detect different levels of touch depending on how hard you press? This is all thanks to 3D Touch! Check out how to add 3D Touch quick actions to your iOS apps.

Together with iPhone 6s, Apple introduced 3D Touch. This feature is able to detect different levels of touch, depends on how hard you press. It is basically a third dimension in the user interface.

3D Touch – How it Works

With this feature, the user gets access to an app’s quick actions by pressing hard on the home screen icon of the iOS application. By hard pressing a view inside an app, the user can see a preview for additional content and features.

3D Touch - how it works

3D Touch – how it works

Getting Started with 3D Touch quick actions

First of all, to implement 3D Touch quick actions in your iOS app, you have to define UIApplicationShortcutItems array in your app’s Info.plist file. It should look like this:

3D Touch quick actions in your iOS app

 

You should define one static quick action with the following parameters:

  • UIApplicationShortcutItemTitle (required) is a string describing the quick action.
  • UIApplicationShortcutItemSubtitle is optional text displayed below (remember it is a single line). If you haven’t added a subtitle your title will be able to be shown on two lines.
  • UIApplicationShortcutItemIconType is an optional string that represents your icon in the Assets file.
  • UIApplicationShortcutItemType (required) is a required string that identifies the quick action.

You can find a list of all available shortcut items with full descriptions here (Table 2).

Now, you have one 3D Touch quick action in your iOS app:

3D Touch quick action in your iOS app

3D Touch quick action

To handle this action, you need to implement the performActionForShortcutItem method in AppDelegate.swift:

 

 
func application(_ application: UIApplication, performActionFor shortcutItem: UIApplicationShortcutItem, completionHandler: @escaping (Bool) -> Void) {
        
        completionHandler(handleShortcutItem(withShortcutItem: shortcutItem))
}
 

You call completionHandler with a Boolean value, which you get from handleShortcutItem(). True means that you have succeeded with handling your quick actions. False means that you have not succeeded.

 

enum ShortcutType: String {
        case print = "Print"
    }

func handleShortcutItem(withShortcutItem item: UIApplicationShortcutItem) -> Bool {
        
        guard let shortcutType = item.type.components(separatedBy: ".").last else { return false }
        
        if let type = ShortcutType(rawValue: shortcutType) {
            switch type {
            case .print:
                print("quick action handled!")
                return true
            }
        }
        return false
    }

 

Here you have the method, handleShortcutItem(), that takes UIApplicationShortcutItem as an argument and returns a Boolean value depending on the success / failure of the quick action. This function checks if the passed shortcutItem is the one you are expecting. Then returns true if the type of quick action matches a type in enum ShortcutType. So, all the quick action does is print text on the console screen.

Okay, it was super easy and everything works fine. What you did was to define a static array of quick actions. And how about changing actions dynamically?

Dynamic 3D Touch Quick Actions in iOS

Here is your answer to this issue:

Once you have registered a quick action, it cannot be changed. So what you need is to set the characteristics (title and type – they are both required) to UIApplicationShortcutItem during initialization, just before registering them.
To do that, drag a button to your view and add this code to @IBAction (touch up inside).

 

 

if let bundleID = Bundle.main.bundleIdentifier {
            
            
	let type = bundleID + ".DynamicAction"
	let icon = UIApplicationShortcutIcon(templateImageName: "ic_add_circle_outline")
            
	let newQuickAction = UIApplicationShortcutItem(type: type, localizedTitle: "New Dynamic Action", localizedSubtitle: nil, icon: icon, userInfo: nil)
	var existingShortcutItems = UIApplication.shared.shortcutItems ?? []
	print(existingShortcutItems)
	
	if !existingShortcutItems.contains(newQuickAction) {
                
		  existingShortcutItems.append(newQuickAction)
		  UIApplication.shared.shortcutItems = existingShortcutItems
	}

} else {
    print("bundle Id is missing")
}

 

You create newQuickAction with a new icon and type which is bundleID + name and title. Then, by assigning your action to shortcutItems in a shared instance of UIApplication class you register it. Finaly, to be prepared for a new coming action, you should also change the enum ShortcutType and handleShortcutItem method:

 

enum ShortcutType: String {
        case print = "Print"
        case new = "DynamicAction"
    }

func handleShortcutItem(withShortcutItem item: UIApplicationShortcutItem) -> Bool {
        
	guard let shortcutType = item.type.components(separatedBy: ".").last else { return false }
        
	if let type = ShortcutType(rawValue: shortcutType) {
		   switch type {
        case .print:
            print("quick action handled!”
               return true
        case .new:
            print("dyamic quick action handled!")
        }
	}
	return false
}

 

As a result, you have two actions now! It should look exactly like this:

Dynamic Quick Actions in iOS

3D Touch – static and dynamic quick actions

Summary: 3D Touch Quick Actions Tutorial

Remember that after the installation of an app, the system will register only static quick actions. Dynamic quick actions in iOS can be registered at runtime.

An important fact is that the system limits the number of quick actions. Static actions are displayed first and if there is still some space then an appropriate number of dynamic actions are shown. Keep that in mind.

Apple gives some tips on how to use this quick actions. For example, every quick action should have an important value for the users, a clear title and a matching icon (but not an emoji). You shouldn’t use quick actions for ease of navigation or notifications also. See more at iOS Interface Guidelines.

Follow our blog, because the “3D Touch Peek and Pop Tutorial” is coming soon.

Check out other iOS development tutorials on our blog.

Szymon Wereszczyński

Szymon is our iOS developer who checks the news from Apple every morning. After hours, he always practices: making music and gym day by day. And he is getting better at Zaven's table-soccer competition!

Popular posts

Effortless deployment of Azure CosmosDB JS functions with GitLab-CI

Effortless deployment of Azure CosmosDB JS functions with GitLab-CI

Working with CosmosDB JavaScript triggers and stored procedures can be problematic, especially when your application consists of three or four separate development environments. The solution we need is found in the effortless deployment of Azure CosmosDB JS functions with GitLab-CI.

Read more
Interviews with startup founders: Fonn Byggemappen

Interviews with startup founders: Fonn Byggemappen

Fonn Byggemappen is an iOS, Android and web application for construction industry projects. The tool’s co-founder Jan Tore Grindheim told us about the beginnings and crucial moments of the app.

Read more
Core ML: Machine Learning for iOS

Core ML: Machine Learning for iOS

You have probably heard phrases like “Machine Learning” or “Artificial Intelligence” without knowing exactly what they mean. In this article, I will shed some light on “What Machine Learning is” by showing you a Core ML iOS sample.

Read more
Mobile Apps

Get your mobile app in 3 easy steps!

1

Spec out

with the help of our
business analyst

2

Develop

design, implement
and test, repeat!

3

Publish

get your app out
to the stores

Contact us

Hire us now!

back to top