Thinking Through Code
“Refactoring” is a term often bandied about when coders really mean “rewriting”. I think refactoring specifically requires a set of tests to demonstrate that the code continues to look the same from the outside even though the insides have changed dramatically. i.e. the tests pass before and after each refactoring step.
There’s a lot you can read up on on the ideas of Refactoring and Test Driven Development in particular but there do not seem to be many demonstrations of how to do it. After spending a good few hours deciphering and understanding Apple’s own Action Extension template code, I thought it would be good to show my thinking process as a demo of trying to understand somebody else’s code and reworking it into something usable. I will also take the opportunity to correct some dreadful naming and improve upon the coding techniques used to take advantage of more Swifty features. This isn’t really Refactoring but it is Thinking Through Code. The test is “can I see the expected image?”
I’m writing this post as I do it so open up Xcode 9 and let’s get cracking…
First, create a New Project. Choose a Single View App and call it ActionExtensionDemo.
Add a New Target, select Action Extension and call it ActionExtension In the next dialog, do not Activate the ActionExtension Scheme. Press Cancel.
Build and run and you get an app with a blank white screen. Fat lot of use that is. This is because the main target app is just a container for the Action Extension which is what we are really interested in. It is an extesnion that expects an image so go to Photos, select an image and tap the share icon in the bottom left.
After tapping the share icon, you will se a row of grey icons at the bottom of the screen. these are Actions.
Our Action is hidden anyaway inside the More menu at the far right of the bottom row. Swipe left until you reveal it.
After tapping More, we now have to scroll down to find our ActionExtension.
Now switch it on and drag it to the top…
Tap Done to make the ActionExtension available to use from other apps. When you tap the share icon our faceless extension is available for use. Tap it and it will show a view containing the image. Voila. The Apple template works. We can modify it for our own purposes. Before being able to do that we should try to understand it. Have a look ActionViewController.swift in Xcode.
It’s obscure stuff to say the least. And it’s buggy:
- Done button does not work after using on a photo in Photos, forcing user to force quit Photos.
- Does not show image when used from Twitter app. But Done does work in this case.
This is not an auspicious start. The 63 lines of code provided by Apple in ActionViewController.swift don’t seem to work well…
Let’s Log
So how to deal with this? Normally, I’d step through the code but as this an extension that seems hard to do. So we are left with one of the most primitive tools a coder has: print stuff out. But again as we can’t easily attach a debugger this is also hard. Until we remember about the Console app on the Mac. Type “Console” into spotlight and open the app. You can select various devcies to see a log of what is going on in each. Apple engineers aren’t afraid of spamming this with NSLog() so we will have to filter out for messages we are interested in.
In the ActionExtension group, add an empty Swift file called, ConsoleLogger.swift. Let’s create a ConsoleLogging protocol and extend it with some default functionality.
We are simply facading NSLog() for this example. Now we make the ActionViewController adopt ConsoleLogging by adding the following to the end of ActionViewController.swift:
One of the things I love about Swift is that we can extend exisitng code easily like this.
Let’s start logging messages to the console and filtering them out by filtering for messages with “[ActionExtensionDemo]” in them.
Make the first line of viewDidLoad() in ActionViewController.swift log a message:
log("viewDidLoad")Now build and run the app in an emulator, go to the Photos app and display a photo in the Action Extension. Set your search in the Console app to search for the first characters of “[ActionExtensionDemo]” until you are satisifed that you have made contact. You should see somehting like this:
Done is Done
The first thing to do is to fix it so that you can exit Photos after using the extension without having to force quit. Adding a log message in the done() function of ActionViewController confirms that the Done button is not responsive if an image loaded successfully. But if you try to use the Action on a non-image, say a News article, the Done button works as expected.
I tried rewiring in Interface Builder and adding another item to the Navigation Bar that triggers the same done() action but to no avail. Navigation Bars are on their way out as a UI element as the top of the screen is increasingly hard to reach so I decided to ditch it in favour of a Toolbar at the bottom of the screen.
Add a Toolbar at the bootom of the screen and drag the Done button onto it. Now delete the Navigation Bar and move the Image View up and resize to fit.
At this point, Autoulayout is probably going to complain so delete the constraints and add new ones as follows:
- Pin the Toolbar to the bottom and sides of the Safe Area.
- Pin the Image View’s bottom to the top of the Toolbar.
- Pin the Image View to the top and sides of the Safe Area.
You should end up with interface builder looking like this:
With no code editing, we have fixed the the Done button! I’m not at all certain why this didn’t work in Apple’s template code but it is working now so I guess we’ll have to accept this. (Please let me know if you have some intel on why the Navigation Bar stopped accepting input in the first place.)
Get Andrew Eades’s stories in your inbox
Join Medium for free to get updates from this writer.
I actually want to be able to use my Action Extension from within the Twitter app so it’s no good if this doesn’t work. Try sharing an image from Twitter and using this extension. The image does not show. It took me ages to figure out why and I will show no mercy in blaming the culprit when we come to it. But with the hindsight I have gained, let’s take a look at the code and see if we can simplify or make sense of it.
This code just looks like trouble to me. The relentless marching to the right, the forced unwraps using !, the imageFound flag. These are all bad code smells to me. There’s some async code in there as well for loading the image into the image view and no error handling. Hmm. Where to start?
When I originally did this I was not as methodical as I’m about to be. And I suffered from that. I’m going to simplify this code first, add error handling and then see if we can get it to work how I want.
To get rid of the nested for loops and if statements we need to draw on Swift’s more functional concepts. That is, we are going to use map, flatMap, and filter to help us out here.
First let’s extract the code at the centre of the fors and ifs into a method so we can focus on the flow:
You can do most of this using Xcode’s Refactor/Extract method but you have to move the weakImageView = self.imageView line up and I changed the signature of the function as well by adding from.
Our viewDidLoad() now looks like this:
There is still a lot of stuff hanging right out there. Let’s get rid of the loops. Basically, the loops are iterating over a list of NSItemProviders that come as attachments to the list of NSExtensionItems. So we have 2 nested for loops to iterate over all potential NSItemProviders.
I’m going to replace it all in one fell swoop and remove the need for the imageFound flag. And make it much safer code to boot.
Here’s the new viewDidLoad():
Simple, eh?
What we’ve done here is express the original coder’s intent as a mapping of the inputItems array into a single image provider and then called loadItem() on that. Rather than use lots imperative code which leads to too many opening braces, we’ve taken a much more declarative approach.
We’ve said that:
- The attachments are all the extension items’ attachments (using flatMap).
- The imageProviders are the attachments as ItemProviders of images.
- We are only interested in the first image provider’s image.
We don’t need the imageFound flag nor do we need to break out of nested loops. We use mappings and filters to reduce the initial inputItems array until it is just one item that we know is an image provider.
We also remove nil pointers by filtering them out and then unwrapping the optionals that are left.
I’ve also used guard…let…else statements to check for error conditions.
I’m happy that this code is better and that I’ve understood the previous version enough to “refactor” it. Now for the massive gotcha.
One thing a compiler can’t do yet and tests can’t help with is bad naming. It took me quite a while to work this one out but here it is:
private func loadImage(from imageURL: NSSecureCoding?)Remember that I refactored this from the original code but the error was brought along into the refactoring. Actually, it was doing this refactoring (way too late) that made it more obvious to me.
The variable passed as “imageURL” is not an image’s URL, it’s not even a URL. It’s type is NSSecureCoding? and it is cast to a URL within the function, silently failing if it isn’t castable. With all the forced unwrapping going on previously this was easy to miss as just a way to get from the older Objective-C NS-APIs to Swift. The easy assumption to make at this point is that the only possible value that can be handled here would be an image’s URL. How else could it have made it through the checks against kUTTypeImage? It turns out that this is a terrible assumption to make.
Rather than fail silently, we should let the user know.
Add this extension to the bottom of ActionViewController.swift.
This is a helper function to show an alert message and optionally cause it to dismiss the Action Extension when the alert is seen by the user. This is the most common case as it is likley an error so we set a deafult value of true for shouldCloseExtensionWithAlertDismissal.
Now we add a call to showAlert() to everywhere that we see a return statement in the code as we are only returning prematurely if we hit a problem.
And we refactor loadImage() a bit so we can test it’s argument is a URL before carrying on. We end up with this:
After running this and trying to use our Action on a News article we get the expected alert:
Testing on my phone and trying to use the extension on an image embedded in a tweet, gives the error message “Item is not a URL” which eminates from loadImage(). With this knowledge we know that the item passedthte test to see if it was an image type but did not provide a URL to load an image. What is going on? At this point I was forced to RTFM and discovered that NSItemProvider.loadItem() could provide a variety of things in its completion handler. The item could be one of the following: URL, Data, Filewrapper, or UIImage. Obviously, a URL was expected as the template names it “imageURL” but a URL might not be the item provided. With this new knowledge, we can handle for the other cases. It transpires that my embedded Twitter image was being provided as Data so once I’d handled this case it started to work.
Here’s a rewritten loadImage():
And now everything works perfectly.
The moral of this story is that when looking at this code, I was suckered into thinking that all the forced unwrapping of optionals was just the barrier between the old Objective-C world, where the extension APIs come from, and the new Swift world. This led me to assume that the casting of imageURL to a URL was a formality rather than anything that could fail. Since it was called imageURL, I’d made the incorrect assumpotion that this was all it could be. In my particular case imageURL was actually of type Data.
The complete project can be found on github.





