Topics

#92: Shared Links Extensions 📰🔗

Topics

Shared Links Extensions arrived with iOS 9 and OS X El Capitan this year. They allow our app to insert content into the users' Shared Links section of Safari on iOS or OS X. Let's add one to our fictional Little Bites of Cocoa app so users can see all the latest Bites right inside Shared Links.

We'll start by going to File > New > Target... in Xcode and choosing a Shared Links Extension.

This will provide us with a new group in our project with one file inside, called RequestHandler.swift.

In this file there's one function called beginRequestWithExtensionContext(context:).

iOS will call this on our extension and that will be our cue to run whatever code we need to load the content we'd like to show in Shared Links, then return it in the form of an array of NSExtensionItems.

We'll return them via a completion function on the context we're passed in.

class RequestHandler: NSObject, NSExtensionRequestHandling {
  func beginRequestWithExtensionContext(context: NSExtensionContext) {
    Bite.loadNewest { bites in
      let extensionItems = bites.map { bite -> NSExtensionItem in
        let item = NSExtensionItem()

        item.userInfo = [
          "uniqueIdentifier": "lboc-bite-\(bite.number!)",
          "urlString": "https://littlebitesofcocoa.com/\(bite.number!)",
          "date": bite.publishedAt
        ]

        item.attributedTitle = NSAttributedString(string: bite.title)
        item.attributedContentText = bite.content
        item.attachments = [
          NSItemProvider(contentsOfURL: bite.imageURL())!
        ]

        return item
      }

      context.completeRequestReturningItems(extensionItems,
        completionHandler: nil)
    }
  }
}

Lastly, we'll install our app, then head to Shared Links in Safari. We'll enable our extension under Subscriptions.

Success!