Xcode UI Tests problems

The problem with Xcode UI Tests

A little background

Ah, yes, automated UI tests. You cannot consider yourself a good developer and not love them. Or at least do them. Have tried them? Know about them?

To me, they are a lot like urban legends. Everyone knows about them, but not so many people claim to have seen them in action. And even fewer have actually seen them in action. But why is that?

Naturally, most often it’s the case of “Ain’t nobody got time for dat!”. But beyond… why do they tend to be overlooked. My theory is that they are simply too frustrating and tedious. There’s a major effort in making them easy to write and reliable, but really? Are they?

Lets look at Appium, for instance. It was supposed to be this great new tool that makes testing a breeze. And cross-platform too! But in reality it is (in my opinion at least) fragile. It can be slow, you have to wait for updates after a major Xcode release, and it’s not exactly cross platform in the real world. It comes with so much pain and maintenance costs, that it is often impractical to use.

And what about Xcode UI Tests? It was a huge deal when it was announced several years ago at WWDC. I mean, even before, we had UIAutomation, but surely, Xcode UI Tests are better, right? And yes, they are, but to be fair, it wasn’t that difficult to be better than UIAutomation.

The problem with UI Tests

Don’t get the wrong idea, I love the prospect of UI Tests. It would be an ideal way to test applications. It’s not manual, it’s relatively fast and it’s (almost) black box. Also, it’s really fun watching the simulator or your test device come to life and start tapping on buttons on its own.

That being said, why did I say it would be an ideal way to test?
It’s just because it often proves unreliable. There are just too many variables. So many moving parts need to come together in order for a test to run and execute to completion. Moreover, if you really want a black box test, you will have to live with your application accessing remote and/or persistent data. And by doing that, you become exposed to network issues and inconsistent state between test runs.

Additionally, if you look at the tools themselves, they can also be a bit unreliable. Just like I wrote about Appium above, it would be unrealistic to expect it to just work. You have to fight it all the time. And unfortunately, after many long fights, you will be tempted to abandon your tests.

The problem with Xcode UI Tests

With the release of Xcode’s UI Tests, one would expect that things would get better. And not because everything Apple touches magically turns into gold as many people believe, but because only they have the power to break through all the sandboxing and private API barriers and make something good happen. But I still feel there’s plenty to be desired.

Limited API

A major problem with the new Xcode UI Tests is that the programming interface is quite limited. Also, the documentation is seriously lacking. Now this is really unlike Apple. Usually, you’d get an API reference and a programming guide. But with UI tests, we get close to nothing. It almost feels like it’s incomplete.

Basically, all Apple provides is the User Interface Testing and the XCTest reference. Even doing a web search for it, doesn’t yield as many results as expected. I wonder why that is. Do people not understand it and avoid writing about it? Or they just ignore it?

Unintuitive classes and methods

While writing UI tests, you are never working with the classes you are familiar with from development. It’s always a facade (or proxy) of the real thing. Whether it’s XCUIElement, XCUIApplication or XCUIElementQuery, you will never be able to use the methods you are used to.

Text fields, switches, labels and buttons… they all have the same interface – they are hiding behind XCUIElement.

One nice example of how primitive the interface is, would be typing text in a text field. You’d expect there would be a property for that. But there isn’t. You have to type the text yourself. At least you don’t have to do it one character at a time. However, you DO need to make sure the text field has a first responder status by tapping on it. If you fail to do so, you’d get an exception. Additionally, if you want to set the text, not just append, you need to clear any previous characters manually. For that, you need to find the code for the backspace button (“\u{8}”, you’re welcome) AND also calculate how many times to type it in order to clear the whole field.

So, to do something so trivial and basic as setting the text on a text field, you need to:
* Tap on the field to make it a first responder
* See how many characters it already has
* Type backspace just as many times
* Type the desired text

And even though it takes 3 minutes to write a utility function for that, it just shows how unrefined the API really is.

Poor asynchronous operations

Sure, being asynchronous is probably not the highest priority item on a UI testing framework’s agenda. But shouldn’t it at least be in the top 5? Lets face it, some tasks take longer than others. And in the app scene nowadays, a server-side component is almost a must-have. So it should come to no surprise that tests needs to wait sometimes.

To be honest, Xcode UI Tests do. In a way… Sort of… sometimes. It’s of course quite blurry, since the resources are lacking, but here’s what I understood:

Waiting to idle

Yes, Xcode UI Tests “wait”. As far as I understand, waiting “for the app to idle” means that it will detect that there are animations still performing and wait for them to complete. But after they all finish, and some element you need is still not there, (boom). Assertion failure. Oh, well!

Waiting for long running tasks

Xcode UI Tests will not wait for several seconds in case something changes (by default). I think that was the case with other testing platforms, but not Xcode UI Tests.

Waiting for expectations

That being said, Xcode UI Tests support some sort of asynchronous tasks using expectations. And by “some sort of”, I mean that most cases are possible to achieve but sometimes quite annoying to implement. Spoiler alert – waiting for element to disappear or waiting an explicit time interval.

The basic idea is to create an “Expectation” with a predicate (most often the predicate is that an element exist, or a table has more than 0 cells). Then you wait until those expectations are fulfilled with a given timeout. If the predicate doesn’t evaluate to true after the timeout expires… bad news. There’s also a completion handler that gets called after the timeout but the annoying part is that there is nothing you can do there to avoid the test failure.

Most of the time, an expectation would look like this (in Swift 2):

_ = self.expectationForPredicate(NSPredicate(format: predicate), evaluatedWithObject: uiElement, handler: nil)
self.waitForExpectationsWithTimeout(timeout) { (error:NSError?) in
  if error != nil {
    print("*** Failed expectation for test: \(message)")
  }
}

For now, expectations don’t look too bad. The problems emerges when you realize how often you have to write that same code. As I said, every operation that might take a non-trivial amount of time, needs to have that. Normally, pushing or presenting a new screen wouldn’t require it. But then again, sometimes it does. At some point you stop caring and put it there as well.

On that note, what really gets on my nerves is that this is hardly explained in the documentation. Even more, using the famous recording mode, such code will never be generated. It will only generate taps making you assume you don’t need the expectations. Then you start running your tests only to find they often fail. I wonder how many people got too frustrated at that point and gave up.

Waiting specific time interval

As hinted above, this is something that’s especially frustrated about Xcode UI Tests. I don’t think it’s an edge case that developers might want to wait an explicit amount of time and then proceed. Even in UIAutomation, you could achieve that using action timeouts:

UIATarget.localTarget().pushTimeout(15);
UIATarget.localTarget().popTimeout();

It’s not ideal, because that’s just the time UIAutomation waits between actions, but still, it worked. However, Xcode UI Tests don’t have that…
If you want to wait explicitly, you have two options (at least I know two ways).

One would be a good old “sleep” on the thread. But lets face it – the intersection between programmers that “sleep” ( :) ) and programmers that automate tests, is not that big.

NSThread.sleepForTimeInterval(15)

Alternatively, some GCD magic can be employed. It’s a bit messy, though. But it’s a cool hack you can use to brag about when you meet your nerd friends:

func checkFor(predicate pred:NSPredicate, onElement:XCUIElement, afterDelay:NSTimeInterval, timeout:NSTimeInterval = 3) -> Bool {
  let waitExpectation = expectationWithDescription("Delaying for predicate \(pred) on element \(onElement)")
  let waitTime = dispatch_time(DISPATCH_TIME_NOW, Int64(UInt64(afterDelay) * NSEC_PER_SEC))
  dispatch_after(waitTime, dispatch_get_main_queue()) {
    waitExpectation.fulfill()
  }
  self.waitForExpectationsWithTimeout(afterDelay + 0.2, handler: nil)
  return pred.evaluateWithObject(onElement)
}

That’s not the easiest code to understand so lets explain it a little bit. We make an expectation and start waiting for it because we need to block the process for a while. And the trick is to automatically fulfill that expectation just before it “expires”. So we use grand central dispatch to fulfill the expectation after the timeout we want to wait. At that point, the process resumes because there is no expectation to wait for anymore. Finally, on the last line we evaluate the predicate directly, knowing the timeout has already passed.

Note: Another limitation about expectations is that there can only be one at the same time. That means you cannot wait for several things at the same time.

In general

I complained a lot in this article but I still want to end on a positive note. I actually like Xcode’s UI Tests, and I do use them. I’m convinced that they have a lot of potential. But on the other hand, they still need a lot of work until they become easy to use and reliable. it is all too easy to hit a brick wall with them and quit. After you go over the initial hurdle, it gets easier and you start seeing more and more potential with them.

I’m planning on writing a complete guide on using Xcode UI Tests in order to share my findings and hopefully spare some people a lot of hair pulling. But until then, only this rant about them will be available. Stay tuned!

iOS/Mac open source world

This post is part of Issue01 of the DevMonogolue Magazine. Whereas the following post contains all the information, you might consider looking into the whole issue for better formatting, context and additional articles.

In this article, we will delve deeper into the world of open source projects, specifically for iOS and Mac. And by that, I mean mostly iOS. On Mac, many of the really good open source applications are actually cross platform and more native to Linux than Mac OS.

Going to GitHub and starting a search for either Swift or Objective-C yields mostly frameworks and chunks of reusable code. Whereas this is really useful to other developers for learning and sharing, here we will focus on complete applications (with some exceptions). Something you can actually run and see.

Lets get started and see some prime examples of the Apple open source community:

Artsy

Artsy is definitely an exemplary company in regards to open source. Most of what they do is out in the open. It’s always on GitHub and it’s always free and open source. They even use the MIT license, so you are free to do whatever you like with their code.

It probably takes a lot of courage to let go of all your intellectual property like Artsy does, but I guess it worked out in the end. Even regarding this kind of structural aspect of the company, they are really open to sharing. You can find all kinds of information on their blog about virtually any aspect of their operation.

For example, you can find their thoughts on going open source in this article. They bring up a lot of good points regarding the threats and opportunities of open source software. Having a management team with a technical background definitely helps selling the idea, but the text makes a very good argument about it.

Companies revolve around ideas, and understanding what your core value is important. A company who make money purely off selling their apps could be easily copied, and OSS by default won't work for them. Artsy is a platform, but OSS by default can work for us because a technical platform is just one aspect of what we offer.
-- OSS expectations, Artsy blog

This is a really solid point, especially regarding mobile. Users are expecting to get apps for free and paid applications are getting less and less popular. Most companies don’t really expect revenue from the App Stores. Their applications are solely there to complement their business. So why hide it? It’s a code base specifically tailored for a propriatary service in mind and doesn’t give much (if any) advantage to your compatition. Unfortunately, looking at the majority of apps in the AppStore, most companies don’t seem to share my vision.

Another great contribution from Artsy to the open source world, is the way they segment their code into libraries and more specifically how they manage those library’s lifecycle. Getting a chunk of code and making it reusable by turning it into a library is a great way to encourage other developers to integrate it for their own projects. But you can also say it’s more about code quality than being open and sharing knowledge. And that’s surely true. By no means is open sourcing only benefiting others. By thinking about the community, you also better stucture your own code. And that by itself is quite powerful. This is actually something the Artsy team talked about in their How we Open Source’d Eigen article.

3 months on the way we operate has changed. We're a lot more organized, and the Eigen repo is easily the most well run project on the mobile team. It has active milestones, that represent long term goals and the current sprint. We discuss a lot of the interesting cultural choices publicly on issues and in our mobile team repo. Having this app in the open, and the experience of doing so has also improved our workflow on other apps.
-- "How we Open Source'd Eigen" post, Artsy blog

I guess people start working differently if they know someone could be watching. It’s probably the same difference between working alone in a dark room with your monitor facing the wall and working in the middle of a huge open office with everyone looking into your screen. It’s just harder to hide something embarracing so you tend to avoid it.

But going back to extracting code into frameworks, Artsy does something that would make many managers cringe. When a developer commits to creating a library out of some pile of code, they do so in their own name in GitHub. Effectively, this developer owns the code, not the company. It sounds strange at first, but first of all the code is open source either way, so everyone can use it. And secondly, their idea is that even if that developers decides to leave the team, he is still the owner of that library’s code. So maybe after resign, they will continue working on the code base. And since it’s 100% open source, Artsy can still use it. Awesome! You can read all about that in Issue 22 of Objc.io.

So, in conclusion, there’s a lot we can learn about open source from Artsy. It’s an excellent example of a company that is not scared of open source, but actually leverages it to create a dynamic and vibrant development environment. I didn’t write much about what their business is about, but I encourange you to [go to their website][Artsy website], download their apps and start using their great technology.

Companies like Artsy can show us a lot about monetarising open source software and doing business in the open. I hope it inspires people to be less scared of uploading their code for everyone to see. But that’s not what open source is entirely about. It’s about the little people. The developers that are driven by desire to create something for themselves but also shared it with others so that everyone can use it. The projects that are not made because of money, but because writing code can be fun. Which brings us to another amazing project:

MiniKeePass

Are you using a password manager? If not, you should. A lot of people nowadays use 1Password for that, but an older, and more open source alternative, is KeePass. So, why would you use it?
* It’s cross platform
* It’s secure
* It’s awesome

And why would you not use it?
* It’s not as flashy as other solutions
* Doesn’t sync your database (at least out-of-the-box)

Without going too deep into a review of the product, KeePass is a really popular, cross platform password manager solution that I personally use and love. But one question remains… does cross platform also include mobile? That’s where MiniKeePass comes in!

MiniKeePass is a mostly independant (from KeePass itself) project that brings the popular password manager to iOS and Android. It’s almost exclusively written by Jason Rush and John Flanagan. It is released under GPL (General Public License). If you wonder what that means, refer to the Open Source Licenses article of this issue. Basically it’s a relatively conservative license that protects the code from being used commercially in closed source projects.

The projects is not in very active development, but it is by no means abandoned. it receives updates with fixes whenever an iOS release breaks something and also gets support for new features as the iOS operating system evolves and gives applications more freedom.

Apart from the usual benefits of an open source project, I think MiniKeePass is an excellent way to learn a little bit about security and encryption. Just clone the repository and see how a world class password manager protects your accounts.

Artsy and MiniKeePass are both great showcases, but they miss one really amazing phenomenon associated with open source software. The community! One of the most powerful aspect of open sourcing your code is to leverage the power of the community and start receiving contributions from all over the world (and become famous among nerds). However, MiniKeePass is a too small project, several developers is all it needs and Artsy is too tied to its own services to benefit the people so much that they start making many pull requests. Of course, both projects have contributors, but it’s not enough for a whole community.

And now, you guessed it! We can going to look into projects with a community around them (which are also nerdy enough to get my attention).

Kodi

Kodi logo

Kodi, or XBMC, is one of those projects that is so big that you don’t know where to start. At its core, it is a media center / home theatre software. Or at least that’s how it started. Howadays, it’s full of so many features, that it is difficult to explain. It’s compiled for almost all the platforms you can imagine, iOS included (but for jailbroken devices mostly). As far as I remember, it also had an AppleTV version several years ago (Yes, before tvOS). Kodi supports all the codecs and protocols you can imagine. It plays radio, tv, connects to (or creates) a DLNA server and is completely extendable and skinnable.

Kodi multi device screenshot

And it’s all 100% open source. A truly amazing project. Millions of people around the world are using it and looking at their GitHub repository, they have (at the time of writing) 480 contributors. Of course, that’s across a lot of platforms, but it makes it even more impressive. It is a whole ecosystem of enthusiasts from different backgrounds, joining forces to build something beautiful. I strongly recommend looking into Kodi’s organisation. The project is really commited to establishing a strong culture between its members. It’s an exemplary work of maintaining projects descriptions, product landing pages, blogs and forums. Right it the README file, people can find all the important links to get them started, they have specific resources for the ones that want to start contributing and you can find all the information you need in the forums.

It is no doubt that a community doesn’t just happen, it’s built and maintained. And Kodi is an ecosystem that shows how that’s done.

To some, open source software has a reputation of low quality. And unfortunately, often you cannot expect the same level of polish you’d find in commercial products. But this is not the case with Kodi. It is a mature project that not only manages to bring a large number of features to its users, but also delivers them with unprecedented quality and taste. You will hardly find something that doesn’t work well or is not really well thought out.

Kodi’s code is released under GPLv2. It’s not the most permissive license but working with some many dependencies – codecs, network protocols, plugins, it is probably hard to use a more “relaxed” license.

Overall, Kodi is a much better option for your home entertainment than most (actually all) Smart TV operating systems. If you are trying to upgrade your home theatre, get an old PC or a Raspberry Pi and setup Kodi on it. Then downloaded one of the many Kodi Remote mobile applications (I definitely recommend the official one for iOS) and get started.

Kodi Downloads

Do you remember how I wrote that we are only going to discuss complete applications earlier in this article? Yeah… I lied a little. There is one framework in particular that is really close to my heart. A framework that saved me so much work recently and was constantly amazing me how well design it was. So naturally, I have to write something about it.

CorePlot

CorePlot logo

CorePlot is a 2D graph and chart drawing framework built for iOS, Mac OS X and tvOS. And one of not so many, I’d say. Most alternatives I’ve seen are targetted towards a specific plotting task and are not very generic and reusable.

CorePlot on the other hand, supports a wide range of graph types (even pie charts) and each graph is customizable in almost every aspect. And with a current version of 2.1, it is a quite mature project.

Discussing CorePlot right after Kodi, the question of community arises naturally. The project is, I think, popular, but it definitely doesn’t have a whole culture around itself. It only has 20 contributors in GitHub so far. But that doesn’t mean it is not welcoming to newcomers. Looking into the project description and documentation, there is very little to complain about. All the essential information like the license, contribution guide, important links and installation tutorial are very well explained and easy to follow. The documentation is auto generated with Doxygen and it leaves a lot to be desired, but the project contains a sample application which is really excellent. It guides you through most of the framework’s features. If you want to implement something, just find a graph within the sample application, lookup its code and copy it. That simple!

CorePlot sample project

The code is released under an MIT license, unlike many of the projects we saw so far, which is very cool of the authors.

So what sets CorePlot apart from others? We already saw several extremely good projects. Artsy was able to build a successful software business “in the open”. MiniKeePass was an application that extended the legacy of the core KeePass community and brought an excellent password management utility to the mainstream mobile platforms. And Kodi was an entire software suite bringing all the features you might imagine into your living room’s enterntainment system, and also building a massive community of loyal users along the way. What could CorePlot possible bring to the table to compete against the others?

One of the most important aspects of code reusabilty is good architecture, intuitive interface, loose coupling and high cohesion. Obviously, if we want to use the same code in different settings, it has to be abstract and very well segmented. But that’s easier said than done and all developers know that. it’s more of an art than a process. Many have tried and even more have failed.

Looking back at the specific case of CorePlot, the problem that framework is trying to resolve is inherently difficult. There are lots of components in a graph and there are more types and styles of graphs that any of us can imagine. So how do you create a library that’s, at the same time easy to comprehend, fully customizable and well structured? Well, I have no idea… but it seems the CorePlot authors sort of do.

The framework itself is so big and the architecture and core principles behind it so deep that it would be impossible to explain in this article. In fact, it really deserves a whole dedicated issue (coming soon?).

What I can tell you right here is that the framework does its best to give you freedom to access and customize every element in your graph and still keep a consistent inteface in order to keep the API managable and relatively easy to understand.

Not going too deeply into that, the way they achieve that is by incorporating a “style” object into most elements that you see on screen. These styles have mostly the same interface, so you always know how to change a color or increase a font size. And if that is not enough, often you have on option to substitute a CorePlot element with your own CALayer, effectively injecting your own visuals into the graph. This can be a lifesaver when your design requires something quite unusual and custom made.

And while we are still on the topic of layers, CorePlot is entirely CALayer-backed, which makes the graphs highly interactive and animatable.

Overall quite an enjoyable and useful framework. Even if you don’t necessarily need graphs in your app, it is still worth the time checking CorePlot out and thinking about all the design choices made there. It can serve as an inspiration and example next time you need to layout the architecture for a new app.

Others?

There are, naturally, many other really nice open source applications for iOS and Mac OS. However, it doesn’t make sense to talk about all of them here. Additional projects that I was considering writing about include WordPress for iOS, Wikipedia for iOS and Hammerspoon – a desktop automation tool for Mac OS. All of those have an interesting story to tell and are an important addition to the open source world, showing that you don’t need to keep your code all to yourself and still get the job done.

In in order to cut this article short before it gets too long, we will not be covering those projects. I hope that the ones we discussed were enough to get you inspired and encourage you to develop in the open. Unless you have something really special to hide, it is probably worth thinking if you can benefit from sharing your code with the world, both for the sake of helping others, and also helping yourself. Even if you cannot build a community around your product, keeping everything for the world to see, might have a highly positive effect on your business. As they say:

You can write much better code with a monitor facing the entire office than if you are stuck alone in a dark basement.

Using teams in Apple Developer Center

How to manage your iOS development certificates and provisioning (the less painful way)

 


How to read this article

The purpose of this article is to bring awareness to the issue of provisioning profile management in iOS and how it can be mitigated using teams in Apple Developer Center.

If you’re reading this because you want to fix a provisioning related issue, and you don’t feel like reading anything more, feel free to skip the next few sections and head over to “Summary” directly.

If you’re reading this because you are curious about the topic, feel free to continue reading in sequence :).


 

The rant

Normally articles on Dev Monologue are quite cheerful. But this time their usual positive nature, will be substituted by a cold and dead serious theme. Provisioning profiles and certificates…

Oh my god... the horror... THE HORROR!!!!
-- anonymus Dev Monologue reader

The security aspect of the iOS developer program has always been a frustrating experiece, no doubt about that. Most people cannot seem to get their head around code signing. And what makes it even worse is that in every major Xcode release so far, many things get changed and at the end you never know what’s happening.

I’m going to take the liberty of even comparing it to git (and probably earn many people’s despise). Don’t get me wrong – I love git as much as the next guy. However, my observation is that most developers know a workflow of 6 or 7 commands in git that they use and everything beyond that is black magic. Go outside your comfort zone, and what follows is an endless stream of stack overflow threads and ultimately the shameful git clone all over again.

But now imagine that you write git clone only to find out that it doesn’t work anymore. Instead, there’s a “Fix ANY git problem EVAR” wizzard somewhere in Xcode that works as good as Windows’ network troubleshooting one.

I’m actually old enough to have developed for iOS at the times when Xcode had little to do with provisioning setup. You had to do all that manually. Generate a key pair, upload to the dev center, re-generate provisionings, add your devices manually… It was tedious, it was boring, it was confusing. However, once you actually understood what was going on, it got considerably easier to fix code signing related issues.

In contrast, nowadays many things are automated within Xcode. They don’t work… they are not well explained… but they are automated :O.
So problems either get fixed super easily.. or really, really hard. And I’m not really sure about the first because it has never happened to me (ok, ok, adding a device to the portal is much more convenient).

The example

My frustration with code signing reached its peak recently, when one of our provisionings expired. “It’s fine”, I thought, I’ll just renew it. And for the first time in my life I used the “Fix issue” alert in Xcode for its intended purpose. I revoked the old stuff and created a new one. To my surprise everything seemed to be working, which is already weird. A little investigation encovered that it only worked on my machine, everyone else couldn’t sign even after downloading the new provisioning.

Trying to use Xcode's Fix issue wizard

Long story short, I discovered that revoking certificates now also generates a new private/public key pair in your keychain, And ofc… that means the old one can no longer be used and unless you transfer it to all other machines, your teammates can take one rather long coffee break.

My initial thought was that this is horrific! It’s so error prone. And unless you take sick pleasure in reading release notes from Apple, you wouldn’t even know what’s happening. And knowing (unfortunately) many developers, suddenly private keys, using a passphrases like “1234” start flying around in Skype, Slack, email and.. I don’t know… maybe even Facebook.

After my anger settled down, I decided that there must be a better way. I instinctively thought about teams. I knew the dev center supported multiple users, but to be honest, I had never been in a team that used them. So what are they all about?

Teams in Apple Developer Center

The intention is that every person in your team participates in the dev account with his own AppleID. There are three tiers of permissions – team agent, admin and a member. Intuitively, the agent can renew memberships and work with payments and legal documents, a member can work with developement certificates and an admin can work with both development and distribution. You can learn more about team roles in the developer reference.

But the point is different. In that scheme, you generate provisionings on a team basis. This provisioning can be used with several certificates – one for each member of your team.

This is very powerful because now each developer is responsible for his credentials and certificates. Also you don’t have to share private keys with others. Apart from an excellent security practice, this makes it very convenient to work with freelancers (because ofc they shouldn’t have access to company private keys).

And that being said, those new changes in Xcode start making sense. Yes, if you go to Xcode -> Preferences -> Accounts -> View Details, with only one mouse click, you can revoke a certificate and regenerate a private/public key pair, but you’re only doing it for your personal account. Everyone else can continue working undisturbed.

It’s so simple… and obvious… and yet I’m scared to know how many companies don’t levarage teams in Apple Developer Center. Suddenly privisioning setup is a breeze (relatively… and considering the alternative). For detailed steps how to achieve that, please refer to Maintaining Your Signing Identities and Certificates.

Summary

Initially, it might be tempting to use only one iOS developer account across your whole team for provisioning. However, with changes to Xcode and the member center, it is becoming increasingly difficult to do so without encountering code signing issues from time to time. Namely, nowadays it’s way too easy to revoke a certificate from within Xcode, leaving the old private/public key pair invalid. This in turn prevents other team members from being able to run applications on your test devices.

Introducing teams in Apple Developer Center can help prevent that by having each programmer sign apps with a different certificate, all connected to the same provisioning. Even if someone revokes a certificate, he only does so for his own account – everyone else’s workflow remains undisturbed. This brings higher level of security and better organisation within the team. Also, since this is the intended way, you get easier and better support from Xcode. You can turn a mammoth task such as provisioning, into a stramlined process.

To get started with teams in Apple Developer Center, go ahead and read the following developer reference document. For more information on permission tiers, refer to team roles in the developer reference.

Top articles for 2014

Hello guys! It’s this time of the year again. And while I don’t exactly feel the christmas spirit, I can’t help but reflect on what happened this year. And it has been quite the roller coaster (for me anyway). A lot has changed since this time last year. I’ve managed to accomplish many things I wanted to, mainly professionally (unfortunately not so much with my personal life).

Thinking about what happened this last year, this blog of course comes to mind. December 2013 was the time I started it. Back then, I didn’t know if it would be something people would be interested in. And more importantly, I didn’t know if it would be something I would enjoy and stick to. More than an year later, I’d like to think that it is something I’m definitely interested in and have no intention to stop doing. Yes, it takes a relatively long time to maintain (certainly more than I thought it would). But seeing that it helps others solve their problems and also allow me to write about things I found interesting and/or have dealt with at work, is so satisfying that it outweighs the negatives.

Initially, it was my intention to have new content in the blog once every two weeks. Of course, it all depended on how busy I was at the particular time. And lately, I haven’t had much free time for it. However, today I realized that there are 31 posts in the website, written within 13 months, so I guess I managed to keep up the pace.

As you might imagine, there are articles that turn out better than others. I cannot say I love all my content. That got me thinking… Which are my favorite posts from the past year. And I don’t mean which were the most popular. In fact, these two lists would be very different. There are articles that are very close to my heart that just didn’t make it. They get only a handful of views. The truth is that a post’s popularity involves many factors that are not related to it’s quality. Maybe I didn’t optimize it for SEO right. Or maybe it wasn’t something many people encounter in their daily jobs.

Anyway, lets get to the point.

Author’s pick for best articles of 2014

Regular Expressions in iOS

Even though it’s mildly popular among users, the post about Regex is, by far, my favorite. There’s just something about it. I love how it turned out. I decided to work on an example in order to build the tutorial, and something just clicked. I managed to steer readers from one solution to another while explaining what works and what doesn’t. I think it was the first time an article turned out great for me.

WatchKit tutorial

The WatchKit tutorial is one of the more recent posts in this blog but it’s proving to be one of the popular ones. It provides introduction to development for the Apple Watch and features a few code examples to get you started. it’s meant for people who want a brief introduction and don’t necessarily want to get involved yet. I hope I managed to get that message through.

UIPageViewController tutorial

The UIPageViewController tutorial is, no doubt my most popular post. It’s the top most viewed practically every day. I’m not sure why that is, but I’m glad people find it useful. Ever since it came out, I’ve been trying to figure out what I did different with it and apply it to future articles, because it is clearly successful.

NSURLProtocol tutorial

The NSURLProtocol tutorial is also one of my favorites. However, since not many people know about that class and even fewer have use for it, it doesn’t get as many views as it deserves. It’s really cool that Apple decided to put it in the Cocoa framework. It can really be a lifesaver in some occasions. I was so proud to be able to use it in my SimpleEpubReader project.

Unit testing

One of the several practices I wanted to incorporate in my workflow this year was test driven development. And since I couldn’t use it in my day job, I was mainly experimenting with it in the evenings. And I also wanted to share my new knowledge with the internet via a series of blog posts. In retrospect, these posts have probably helped me learn TDD more than they helped anyone else. But still, I hope they were helpful to you as well.

Using the debugger console lldb in Xcode

Not many people nowadays really leverage the functionality given to them by the debugger. Mostly they use it to stop, step over and inspect variable values. And that’s a real shame, because you can do wonders with the debugging console. This article was my way of spreading the word about it.

UIAutomation in Xcode

Automation is something I’ve always been interested in. And if I had the power, I’d make sure Quality Assurance always tries to automate some of the  testing process. And I was surprised to read that Apple developed a tool for that. I played around with it for a while, write a couple of scripts for the applications I was working on and afterwards decided that it might be something people would like to learn about.

AVAudioSession bluetooth support

Oh, Bluetooth support… It was my kryptonite for quite a while. It is so fragile and every time, there is an use case where it doesn’t work exactly as planned. After a week or two of debugging i think I finally figured it out. And since there’s hardly any resources on that, I decided to share my experience with others.

Crash reporting in iOS

There are so many crash reporting frameworks out there that people probably don’t realize that it’s not such a big deal to do yourself. And crashes are not that hard to comprehend – it’s just the OS shutting you down because your application is misbehaving. With a little bit of Unix knowhow, you can have it all figured out.

Testing iOS and Mac applications with ipfw in unreliable network conditions

I’m really proud of this one. Why? Because it’s the very first DevMonologue article ever. My first attempt at blogging. There are many things about it I wouldn’t do today, but it still has sentimental value. I realize that there aren’t many people that would find it useful, but I think it contains some cool information – like some inner-workings of BSD’s firewall.

Swift optional values

This post is part of a Swift vs Objective-C series where we look at new features in Swift and how they compare to their predecesors from Objective-C.

What are Swift optional values?

Optional values are a major weapon in Swift’s arcenal. It’s unlike anything I’ve seen in my professional carrier as a developer, though I’ve read that there are languages with similar concepts. They are designed as a replacement to Objective-C’s way of treating nil references.

Swift makes heavy use of optional values. They are absolutely everywhere. So you better get used to them. The bad news is that they take a little bit of time and practice to get right. In fact, I still have problems with them at times.

Objective-C message dispatch

Let me step back a little bit. Even the most inexperienced iOS developer has noticed that Objective-C deals with pointers to nil differently than Java for instance. For one thing, it doesn’t make the application throw an exception. But why is that? And how?

The second question has a lot to do with the way Objective-C dispatches method calls to it’s objects. In short, it reads the object that the reference is pointing to, and asks it which class it is a member of. Having that information, it finds the code for the right method, based to that class and if everything goes well, calls it. This mechanism is not too strict when it comes to nil pointers. When you try to dispatch a method call using such a pointer, instead of treating it was an exceptional behavior, it fails gracefully by ignoring the invokation.

One might argue that allowing that kind of behavior might result in obscure bugs, just because your methods calls might not actually work. Isn’t it better to just crash and have the developer rethink his code? Well, not necessarilly. Nil pointers DO exist and they are not always signs of incorrect bahavior. Sometimes, a function has nothing to return and it has no choice but providing nil. Does this mean, the application cannot recover? Not at all. If it crashes when you try using a pointer like that, you code will soon be filled with pointless if statements that do nothing but confuse people reading it.

By allowing messages to be dispatched to nil objects, Objective-C code has much less security checks and is, therefore, much easier to read.

Where Objective-C falls short

The previous paragraph has probably made you think that Objective-C is already good enough at handling nil references. However, there are a few exceptions.

First of all, it only works for objects. Values, such as integers, enums and structures are not subject to the same message dispatch mechanism and, hence, don’t behave that way. That means that you have to be aware what type of data you are working with.

Secondly, Objective-C’s synthax does not provide any hint about the validity of returned data. You can never be sure if a method returns nil because an error has occured, or there was simply no data there to supply. You have to rely on your documentation (if you have any) or method name to let others know what it means for that method to return nil.

Nil 2.0 – Swift optional values

As already mentioned, Swift optional values are everywhere. I doubt there was more than a few classes that don’t have them. They are the language’s way of indicating that a variable does not have a value. Normally, a variable or constant points to a piece of data in memory. This is often referred to as binding. A variable is bound to an object. However, what happens when you have a variable, but you don’t have an object to associate it with. A common example of this scenario is a function that has a return type, but given it’s input, there is no data to actually provide. It still has to return something, so a common solution is to get a reference that points to an invalid address or a value that is not acceptable in the context. In Objective-C, methods return nil for objects and special constants like NSNotFound for primitive data types.

Swift handles this situation by the defining the term no value. Swift optional values tell the developer “This variable might have some kind of value, or no value at all”. The “No value” is universally accepted across classes – “No value” for String variables is the same as “No value” for integers or view controllers. That’s how Swift developers have a clear definition of what it means for a variable to not have a valid value.

Swift optional values synthax

Let’s compare a normal variable to a swift optional value definition.

var myVariable: String

This is a standard string variable. And this:

var myOptionalVariable: String?

is an optional string variable. The difference is the question mark at the end. It had to follow the data type. This definition creates the myOptionalVariable variable and associates it with “No value”. Note that “No value” is different than nil in Objective, where it is just a pointer that refers to an invalid location.

You can explicitely specify that you want a variable to have no value by writing:

myOptionalVariable = nil

Accessing Swift optional values

Swift really wants you be aware when you’re using optional values – that’s why it wants you to be very explicit every time you use them. It wants to contantly remind you that you are working with a variable that may not have a value. There are several ways to access an optional. The first one we are going to discuss is forced unwrapping.

Forced unwrapping

This is the easiest way to access Swift optional values. But it’s also the most “dangerous”. It is important to note that using an optional that has no value will cause an exception to be thrown in runtime. So forced unwrapping just instructs the program to get the value without any additional checks. You have to be absolutely certain that there is a value in the variable, otherwise you risk a crash. The following synthax:

 myOptionalVariable!

is how you unwrap your optional.

Optional binding

Optional binding is the safest way to unwrap an optional. Consider the following code:

if let nonOptional = myOptionalVariable {
    // use nonOptional safely
}

Here a new variable (nonOptional) is created to hold the unwrapped value of myOptionalVariable. It is not an optional so it is safe to use it within the if statement’s body. If myOptionalVariable has no value, the code inside the if statement will not be executed.

Implicitly unwrapped optionals

Like many other features in the language, Swift optional values acknowledge common use cases and provide shorter ways to write them. Often, you will have an optional, but right from the start you will be fairly certain that it DOES in fact contain a value. So instead of using forced unwrapping everytime you use them, you can define those variables as implicitly unwrapped optionals like so:

var myImplicitOptional: String!

This new variable is an optional in every way, but it differs in the way it’s accessed. You don’t have to forcefully unwrap it everytime you use it. Just write it’s name without the exclamation mark. It’s still going to raise an exception if there happens to be no value in it, but it spares you the hassle of unwrapping every time (developers are lazy).

Optional chaining

The Swift programming language defines optional chaining as:

“Optional chaining is a process for querying and calling properties, methods, and subscripts on an optional that might currently be nil”

Intuitively, optional chaining allows you to call methods and access properties that don’t necessarily have a value. Like you would expect from Objective-C, if an optional in a chain has no value, the whole expression evaluates to nil.

To back these explainations with an example, optional chaining looks something like this:

nonOptional.optionalProperty?.someMethod()

Note that you can achieve the same call (sort of) by simply typing:

nonOptional.optionalProperty!.someMethod()

The problem, however, is that if optionalProperty happens to be nil, an exception will be thrown. Optional chaining on the other hand fails gracefully by not calling someMethod and returning nil as a result. In fact, all subsequent method calls winthin the same statement will not be called.

As you already saw from the example, optional chaining’s synthax differs by replacing the exclamation mark with a question mark. That’s what instructs Swift to use chainging instead of forced unwrapping.

Conclusion

In conclusion, I’d like to say that Swift optional values are a must have for all iOS developers trying to switch from Objective-C. They are literary everywhere in the API. There is hardly a single class that does not have them. Also, they can take a little time to get used to. That’s why it is important to pay them the attention they deserve.

Thanks for reading!