Developing mobile Apps is a complex task, but it is our job as developers to solve that complexity. And a state machine is one tool that helps us construct simplicity out of complexity. So, in this Xcode tutorial in Swift, I will show you how to use a state machine when developing apps for iOS 9 and OS X 11 El Capitan.
A view controller can easily become a class embedding complex functionalities. For example, imagine a view controller that has to display a user’s profile from a social network. The first situation that we might encounter is that the data are still not available to the app at the moment when the viewcontroller’s view appears. In this case, we have 2 states that we need to handle: data are available and data are not available. The views and the corresponding layout depend on the current state. The simplest way of handling these states could be a boolean. For example, if data are available, the boolean is set to
true, and if the data are not available the boolean is set to… mmmm, wait a second, this is not so simple. But what does “data are not available” mean exactly? Maybe, the data are still not available while we are asking for it from the remote server, or the data are not available because we are unable to retrieve the data from the remote server. Depending on this “unavailability”, we need to customize the UI depending on the real state of the data.
So, now we have 3 states, and our app needs to be able to transition from one state to another. For example, when we receive the data from the server, the UI could change from displaying an animated activity indicator to hiding the activity indicator. But if the application did not receive any data, we should still hide the activity indicator and inform the user that there is no data.
So our initial view controller has evolved. And now we not only need to track our current state, but we also need to track the state transition.
In iOS 9 and OS X 11 El Capitan, a new API is now available to create a state machine seamlessly. This new API is part of
GameplayKit, which is usually used to develop video games. So now I will show you how to use this video game API to manage the state of your application.