Building my first iOS app with Swift 2.0: Session V
Ths is the fifth and final session in building my first iOS app with Swift. The previous sessions are here:
In the previous session I connected real data and moved them between the scenes. In this one, I’ll start with some button animation. When the ‘Add’ button is clicked for adding an Idea, I want to give some feedback to the user. The way to do that is with an Activity Indicator (essentially the “waiting cursor” that tells you something is happening in the background).
I added an Activity Indicator to the AddView, created an outlet for it in the AddViewController and then called startAnimating() and stopAnimating() on the activityIndicator instance. I did have to learn the trick on how to add a fake delay of half a second so that we can block the thread and make sure the indicator shows. It’s like sleep() in C.
All ideas aren’t great ideas, so next I will create the functionality to delete an idea in the list. The interaction here is that a user can swipe a row to see the ‘Delete’ button and clicking on it will delete that row.
This was much simpler than I thought. It required adding a tableView method where I look for the editingStyle of “.Delete”. If it matches, delete the item from the IdeaManager by calling DeleteIdea() and remove it from the tableView.
Great, all this is fun and games, but now I want to persist the data. I will first do this in something called NSUserDefaults that allows you to store data using [key, value] pairs.
Encoding & Decoding
Data that goes in storage need to be encoded and the data read from storage need to be decoded before I can use them.
In the Idea class, I added an init() method that reads and decodes an Idea instance and a encodeWithCoder() method that encodes an Idea instance.
Synchronization using NSUserDefaultManager
I also need a singleton class that saves a new Idea to the storage and initalizes the list of ideas after reading it from storage. The class I created is NSUserDefaultsManager().
NSUserDefaultsManager.synchronize() is called in addButton_click() and in applicationWillTerminate() in AppDelegate.swift so that the list of ideas is saved each time the application exists.
initializeDefault() is called in the ViewController in viewDidLoad(). This way everytime we go to the ViewController, we get the latest and complete list of ideas.
With all this data saving and retreiving functionality, I now have a complete working app!
And the elements in my idea list are stored locally!
And that’s it. Within 5 sessions, I was able to create a simple iOS app in Swift that captures a few text fields and stores them on the phone and retrieves and shows them in a list.
Before doing this, I had never written an iOS native app and nor do I use an iPhone. I plan to clean up the UI and submit this in the AppStore. Let’s see how that process goes.