How to add 3D Touch and open a Tab in iOS using Swift

Last updated on: May 27, 2023

Go to your Info.plist file and right-click on it and press Open As > Source Code and paste the following code between the tag and after a tag:

<key>UIApplicationShortcutItems</key>
	<array>
		<dict>
			<key>UIApplicationShortcutItemIconFile</key>
			<string>3DTouchIconName</string>
			<key>UIApplicationShortcutItemTitle</key>
			<string>3DTouchTitle</string>
			<key>UIApplicationShortcutItemType</key>
			<string>com.yourname.yourappname.tabname</string>
			<key>UIApplicationShortcutItemUserInfo</key>
			<dict>
				<key>TabIndex</key>
				<integer>1</integer>
			</dict>
		</dict>
	</array>Code language: HTML, XML (xml)

OR you can add it manually one by one by pressing the + button in the Property List like the image below

Here’s what every value means:

  • UIApplicationShortcutItemIconFile: The name of the icon you’ll use for the shortcut (e.g. nutrition3dtouchicon)
    The correct size is: 104x104px for @3x and 70x70px for @2x
  • UIApplicationShortcutItemTitle: The title of the shortcut (e.g. Nutrition)
  • UIApplicationShortcutItemType: Here, you add a unique string; with this string, the app will know which shortcut you pressed. You can put the bundleID with the name of your ViewController (e.g. com.johncodeos.3dtouchtutorial.nutrition).
  • TabIndex: Is the number of the tab you want to add (e.g. 1) (The counting of the tabs starts from zero e.g. Tab 0, 1, 2, 3, etc.)

Final step!

Add the following code in your AppDelegate.swift file:

@available(iOS 9.0, *)
    func application(_ application: UIApplication, performActionFor shortcutItem: UIApplicationShortcutItem, completionHandler: @escaping (Bool) -> Void) {
        let handled = handleShortcutItem(shortcutItem)
        completionHandler(handled)
    }
    
    // MARK: - Handling
    
    func handleShortcutItem(_ shortcutItem: UIApplicationShortcutItem) -> Bool {
        if shortcutItem.type != "com.johncodeos.3dtouchtutorial.nutrition" && shortcutItem.type != "com.johncodeos.3dtouchtutorial.workout"  {
            return false
        }
        
        if let index = shortcutItem.userInfo?["TabIndex"] as? Int {
            (window?.rootViewController as? UITabBarController)?.selectedIndex = index
        }
        
        return true
    }Code language: Swift (swift)

In the handleShortcutItem method, we say that when we open the app usually and not from any 3D Touch shortcut, then open the app in the usual ViewController, which is the first one. If not, then open the tab with the number we put on the TabIndex earlier.

NOTE: To test 3D Touch need to have a device that supports 3D Touch (iPhone 6s and above) or the Magic Trackpad 2 to try it on the Simulator.

You can find the final project here

If you have any questionsplease feel free to leave a comment below

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments