Day 67 - 100 Days of Swift

2 minute read

Project 19 (part 1)

Day 67 is the first part of the nineteenth project. It will be a Safari extension that allows you to run some JavaScript on the page, but today you pretty much just spend the whole time getting things configured. You make a new project and you make the extension target. You set up the viewDidLoad in the extension, configure the Info.plist and add a javascript shell file.

First, because extensions can’t be the app on their own, you make a new app and give it a label that, in real life would probably display some set up instructions or help info, but for this project just says “Hello World”.

Screenshot of placing label on storyboard.

Then you add a new Target which is an “Action Extension” called Extension. The default template comes with a MainInterface.storyboard and an ActionViewController.swift. The only thing you change today is to replace the default (and somewhat complicated) code in viewDidLoad of ActionViewController with this:

1
2
3
4
5
6
7
if let inputItem = extensionContext?.inputItems.first as? NSExtensionItem {
    if let itemProvider = inputItem.attachments?.first {
        itemProvider.loadItem(forTypeIdentifier: kUTTypePropertyList as String) { [weak self] (dict, error) in
            // Do stuff
        }
    }
}

This tries to get the first inputItem from the extensionContext and cast it as an NSExtensionItem. If that is successful, it tries to get the first NSItemProvider from the attachments array on the inputItem. If that is successful it asks the itemProvider to actually load the item and give it to us in a closure with loadItem. Inside of that closure is where we’ll actually do stuff tomorrow.

Once that is done, you just add a couple of keys to the Info.plist. You add the NSExtensionActivationSupportsWebPageWithMaxCount key with the value of “1”, to let the system know that we are only interested in receiving web pages. And you add the NSExtensionJavaScriptPreprocessingFile key with the value Action.js to tell it to run the javascript in Action.js when our extension is called.

Finally, you actually add the Action.js file to the project and give it this code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
var Action = function() {};

Action.prototype = {

run: function(parameters) {

},

finalize: function(parameters) {

}

};

var ExtensionPreprocessingJS = new Action

And that is all for today. I don’t really have a great idea how this will work or what use it will have, but I have never built an action extension before so I am excited to try some of this stuff out and see what it looks like tomorrow.

You can find my version of this project at the end of day 67 on Github here.