Topics

#88: Dynamic Shortcut Items πŸ“Œ

Topics

We covered Static Shortcut Items back in Bite #79, when 3D Touch was first introduced. Today we'll be taking a look at their close relative, Dynamic Shortcut Items. These offer the same behavior and functionality (allowing users to quickly jump to a particular section or feature of an app, straight from the home screen) but they can be configured and managed in code, and don't need to be defined in our Info.plist.

Dynamic Shortcut Items are particularly great for offering quick access to things such as user created content. Let's add a couple to our app. We'll use ours to let the user open recently viewed documents.

We'll create a function which we'll call whenever a document is opened in our app. It will update the current set of Dynamic Shortcut Items to match the 2 most recently opened documents.

We'll grab our recent documents, then define a new shortcut item for each one. We can handle tapping a Dynamic Shortcut Item just as we did in Bite #79, by passing a URL in the shortcut's userInfo property then using JLRoutes (Bite #62) to route it correctly inside application(application:performActionForShortcutItem shortcutItem:completionHandler:).

func updateDynamicShortcutItems() {
  let recentDocs = Document.recent(2)
  var shortcutItems = [UIMutableApplicationShortcutItem]()

  for doc in recentDocs {
    shortcutItems.append(
      UIMutableApplicationShortcutItem(
        type: "com.magnus.spaceships.document",
        localizedTitle: doc.name,
        localizedSubtitle: doc.excerpt,
        icon: UIApplicationShortcutIcon(type: .Compose),
        userInfo: [ "url": "spaceships://documents/\(doc.documentID)" ]
      )
    )
  }

  UIApplication.sharedApplication().shortcutItems = shortcutItems
}

Now both our static and Dynamic Shortcut Items are available by force pressing our app's icon on the home screen.

Note: At publish time of this Bite, Xcode did not offer a way to test shortcut items in the Simulator. To generate the screenshot above (and test shortcut items' functionality) this project by Conrad Kramer was used.