Search code examples
ios3dtouch

ios - Dynamically edit 3d touch shortcut list


I want to add a "Continue" shortcut to my game. But when user will finish my game completely I want this to be either removed or replaced by another shortcut. Is this possible? I know 3d touch is handled by ios system, but maybe there are still some options


Solution

  • There are two ways to create shortcuts - dynamic and static.

    • Static are added to the plist and never change.
    • Dynamic can be added and removed in code.

    It sounds like you want a dynamic shortcut, so here's roughly how you would do that:

    To add:

    if #available(iOS 9.0, *) {
        if (UIApplication.sharedApplication().shortcutItems?.filter({ $0.type == "com.app.myshortcut" }).first == nil) {
            UIApplication.sharedApplication().shortcutItems?.append(UIMutableApplicationShortcutItem(type: "com.app.myshortcut", localizedTitle: "Shortcut Title"))
        }
    }
    

    To remove:

    if #available(iOS 9.0, *) {
        if let shortcutItem = UIApplication.sharedApplication().shortcutItems?.filter({ $0.type == "com.app.myshortcut" }).first {
            let index = UIApplication.sharedApplication().shortcutItems?.indexOf(shortcutItem)
    
            UIApplication.sharedApplication().shortcutItems?.removeAtIndex(index!)
        }
    }
    

    You can then handle the shortcut by checking for it in the app delegate method:

    @available(iOS 9.0, *)
    func application(application: UIApplication, performActionForShortcutItem shortcutItem: UIApplicationShortcutItem, completionHandler: (Bool) -> Void) {
        if shortcutItem.type == "com.app.myshortcut" {
            // Do something
        }
    }
    

    Don't forget to check for iOS9 and 3d Touch compatibility.

    You can find Apple developer 3d touch pages here:

    https://developer.apple.com/ios/3d-touch/

    And specifically dynamic shortcuts here:

    https://developer.apple.com/library/ios/samplecode/ApplicationShortcuts/Listings/ApplicationShortcuts_AppDelegate_swift.html#//apple_ref/doc/uid/TP40016545-ApplicationShortcuts_AppDelegate_swift-DontLinkElementID_3