In this article I introduce a small iOS 8 app written in Swift, named SwiftPlaces. I wrote the app in order to get more experience with the language and try out some new features in iOS 8, such as Adaptive Layout.
The source code is available on GitHub.
SwiftPlaces allows the user to search for places by postal code and then view details about a place, including its current weather. It is a universal app, meaning it runs on the iPad…
…and on the iPhone…
I made use of the new support in iOS 8 for using UISplitViewController on the iPhone, as well as the iPad. Due to the Adaptive Layout features in iOS 8 it was only necessary to create one storyboard to cover both device types, which is great news!
There are too many bits and pieces I find interesting to review here, so I suggest you download the code from GitHub and check it out in Xcode 6. Here are a few things to keep an eye out for…
The app calls two Web services from www.geonames.org, namely postalCodeSearchJSON and findNearByWeatherJSON. I wrote a simple class that fetches JSON from a server, named JSONService. Both of the Web services listed above are consumed via that class, which provides closure-based completion handling and the ability to specify which NSOperationQueue the closures run on. Here is an example of fetching a list of places with a given postal code, taken from SearchViewController.
The success closure uses my custom marshal operator function (~>) to move between a background thread and the main thread, as explained here. This allows the app to create data model objects out of JSON, eliminate duplicate entities, and sort them by name on a background thread, leaving the main thread to only display those objects in a UITableView.
Note: I realize that some postal codes include letters, but it seems that the geonames Web service that I’m using doesn’t support them. I didn’t investigate the matter more than a few failed attempts at using Canadian postal codes. A happy side effect of this is the fun way I show an error message if the user tries to search for something other than a number. Check out UISearchBar+ErrorMessage.swift for details.
I decided to write the JSON-to-model conversion code in Objective-C, because Swift’s type safety is at odds with such an inherently “type unsafe” task. There has been quite a lot of activity and debate around JSON processing in Swift, but I found it was just plain easier to write that code in Objective-C. The following code is from Model Builders.m:
There is quite a bit more to explore in the project, so I encourage you to grab the code and check it out. If you know of a better way to use Swift or iOS 8 features than what I’m doing, please tell me about it in a comment.