#10: Action Extensions 🎥


Action Extensions are incredibly powerful. Not only can they accept many different forms of input data, but they can return data back to the original application as well. Let's build an Action Extension to help us sound smart while writing. It will accept a word, let us choose a more intelligent sounding word, then return our selection to the original app.

First we'll add the extension:

File > New > Target... then use the Action extension template.

We grab the input word, then load replacement words:

let c = self.extensionContext!
let item = c.inputItems[0] as! NSExtensionItem
let provider = item.attachments![0] as! NSItemProvider
let textType = kUTTypeText as String

if provider.hasItemConformingToTypeIdentifier(textType) {
  provider.loadItemForTypeIdentifier(textType, options: nil) { (string, error) in
    if let word = string as? String {
      self.loadSmarterSoundingWords(word) {
        dispatch_async(dispatch_get_main_queue()) {

Finally, we'll return our chosen replacement word back to the original app:

func completeWithWord(word: String) {
  var c = self.extensionContext!
  var typeID = kUTTypeText as String
  var provider = NSItemProvider(item: word, typeIdentifier: typeID)

  var item = NSExtensionItem()
  item.attachments = [provider]

  c.completeRequestReturningItems([item], completionHandler: nil)

// then inside didSelectRowAtIndexPath:

You can download a complete working project here.

Run the MakeMeSmarter scheme. Select a word to replace, then press the action button.

Bonus: The project also shows how to retrieve the value back from an extension.