Android Intents with Kotlin

This past fall, I became part of the Ray Wenderlich tutorial team for Android. As part of that team, we are updating the existing Android tutorials using Kotlin along with the latest Android tool set. My first assignment was to update the Intents tutorial.

What is an Intent you ask? Well, Intents and Intent Filters facilitate communications between app components, allowing things like starting an activity, starting a service, or delivering a broadcast.

In the Intents tutorial, you’ll learn the following:

  • What an Intent is and what its wider role is within Android.
  • How you can use an Intent to create and retrieve content from other apps for use in your own.
  • How to receive or respond to an Intent sent by another app.

The updated version of the tutorial can be found here:


Mobile App Development: Consider the Cost, Not Just the Price!

This article was originally posted on my companies blog site found here


When we are talking to customers, either new or existing, we often get asked about the best way to develop mobile apps for both Android and iOS. For many years the options were native versus hybrid. More recently these options have become more complex. The typical reason we get asked this question is that companies are looking to reduce the price of mobile app development. We feel that there is much more to consider in this decision than just the price of development, it’s the true cost that needs to be understood.

At Chariot Solutions, our Mobile Practice focuses on native application development. We didn’t start out with that approach. We worked on native and hybrid apps for our clients. What we have learned over the years is that native simply works best. Sure, for very simple, basic mobile apps it might be worth considering an alternative approach. But we have consistently found that apps that start as hybrid end up suffering from shortcomings that result in sub-optimal user experience or require significant work arounds and even potentially complete re-writes. Based on these experiences, we prefer to focus our efforts on native development resulting in a highly performant, beautifully designed mobile application for our client’s users.

What is Native, Cross Platform, and Hybrid

In order to understand all the aspects of deciding what direction to go with your mobile app development approach, it is important to understand each option and the advantages and trade-offs each has to offer.

At a very high level, native applications are written in a programming language supported by the platform provided SDKs (Software Development Kits). Hybrid and cross platform applications are written in essentially a single programming language and use framework provided software layers to allow developers to generate a user interface and provide access to underlying device features. While this sounds good on paper, the diagram below demonstrates the additional complexity that comes along for the ride.

The following sections provide more detail around the different mobile application development approaches.

Native Mobile Approach

Native mobile apps are written with platform specific languages to directly access the manufacturer provided SDKs.  For iOS, this means writing in either Objective-C or Swift, and for Android the language options are either Java or Kotlin.  Within iOS and Android, each of their supported languages interoperate with the other.


  • It is not possible to exceed the performance of a natively developed application.
  • Immediate access to all platform features via native SDKs (e.g. bluetooth, AR, machine learning, etc.).
  • The similarities between Apple’s Swift and Android’s Kotlin languages make it much easier to cross-train developers and to port the application code between the two platforms
  • More mature tooling in terms of UI development, debugging, and profiling
  • Easier to support multiple device sizes and orientations through the use of provided tooling
  • Built in support for non-phone device types (wearables, TV, Car, etc.)


  • Developers need to be familiar with different tool sets
  • Two languages to learn when cross training developers
  • Maintaining two code bases

Hybrid Approach

Hybrid applications are written using HTML, JavaScript, and CSS, which is then wrapped in an application container that allows it to be treated as an app by the device.  It is essentially a browser-based web app wrapped for the ability to access device features like local storage, bluetooth, and push notification support.  One programming language is used to build the app, which is then wrapped for deployment and distribution.  Examples of hybrid frameworks include PhoneGap, Sencha Touch, and Ionic (built on top of PhoneGap).


  • One programming language to learn
  • Shared code for business logic
  • The same developers and code modules could be re-used for web development.  This is a comment we hear often, but rarely works in practice.


  • Sub-optimal UI performance
  • Reliance on frameworks and the support they will have moving forward
  • Frameworks are so numerous and evolve so quickly that code written 2-3 years ago can become obsolete and riddled with security and performance issues
  • Difficulty in integrating new versions of the frameworks
  • There are more layers of software in the application, which makes debugging and troubleshooting more difficult
  • Tooling is less sophisticated
  • UI/UX tends to blur between iOS and Android, or forces code branching (i.e. if android do this, else do that) throughout the code base in order to differentiate each of the user experiences
  • User Experience can suffer if you decide to stick with common design patterns from one platform; Android users sometimes get offended if your app looks like an iOS app or vice versa.
  • Plugins required to access native OS/device features, which might require a native developer to implement
  • Delayed availability of new platform SDK features

Native Cross Platform Approach

This category is also referred to as just “Cross Platform.”  Mobile applications are written using a single language (e.g. JavaScript, C sharp), and use framework provided APIs to access the underlying native SDKs.  UI components provided by the framework get translated into native UI widgets, allowing close to native application UI performance levels.  While there are numerous frameworks available, currently, the most popular native cross platform frameworks are ReactNative (written using JavaScript) and Xamarin (written using C#).


  • One programming language to learn
  • Shared code for business logic
  • Near native UI performance


  • The same cons as hybrid, plus the following
  • Steep framework learning curve.  While there is a learning curve for native, that skill will still be required when using a cross platform approach.  More on that later.
  • Reliance on the framework providers to continue to exist and evolve along with the native platforms

Mobile App Development Considerations

Now that we understand what each option actually represents, we need to look at the various considerations that go into choosing a mobile app development approach. Most of these considerations go beyond the “development cost” that people speak about. These include things such as the importance of mobile to the overall business strategy and goals, what platforms are really required by your user base, how complex the app is for both business logic and user experience, and the developers you have on staff. Below is a high level comparison of each approach, with the underlying details following the table.

Business Strategy

If your mobile applications are core to your business, then the only real option to consider is native. The user experience quality and performance obtained when developing a fully native app simply isn’t achievable with the other options. How is mobile core to your business when you don’t have a mobile product? As an example, one of our clients is in the home security space. Their main focus is the security system and its sensors and cameras. But the mobile applications provide the user the ability to control the system as well as providing a view into its current state. This makes mobile core to their business. Maximizing UI performance is critical to the user’s happiness and therefore the success of their product.

Platform Requirements

One of the first questions businesses need to ask about their mobile apps is “Who are the users?” In some cases the answer is “90% of the user’s have iOS devices”. One of our clients came to us with a hybrid application that was suffering with significant performance and usability issues. Their clients all used iOS devices (iPads). For their initial version, they chose hybrid “in case they need to support Android someday.” Our recommendation to them was to develop an iOS app optimized for the platform and taking full advantage of what it has to offer. If an Android app is needed somewhere down the road, given the similarities between Apple’s Swift and Android’s Kotlin, it’s pretty straightforward to port the app over.

Another consideration with respect to platform support is access to device specific features. A good example of this is augmented reality (AR). Apple introduced AR to their SDK with the release of iOS 11. Native apps that want to take advantage of this capability could access it immediately, while hybrid or cross platform apps needed either native plugins written or would need to wait for the capability to be added to the relevant framework.

Application Complexity

When it comes to application complexity, there are really two levels: UI/UX complexity and business logic complexity. UI/UX complexity can include things like compound views, custom controls, complicated transitions, the need to support non-phone device types (e.g. wearables, TV, car, etc.). The more of these types of complexity in the application, the higher the need is to take a native approach. UI/UX performance is one of the most important attributes of a mobile app. It directly impacts the user’s perception of the app and therefore the overall success of the app.

If the business logic for an app is complex, we will typically recommend moving that logic out of the app and into the cloud or some other server that can be accessed via an API for all clients, mobile or otherwise. If this cannot be done, this doesn’t mean hybrid or native cross platform is your only option. There are cross platform tools like KotlinNative, ElectrodeNative, J2ObjC, C/C++, etc. that can allow complex business logic to be written once and shared across native apps. Also, with the similarities between Kotlin and Swift, porting complex business logic from one platform to another isn’t as difficult as it once was.


The type of developers you have, or want to have, on staff is extremely important. While native cross platform and hybrid may require developers to know only one language, the reality is that platform experts are going to be required for each platform on which your app is released. There are numerous differences between the platforms in terms of what device features and functionality is available or unavailable on each. Unless you go with a full native approach, plugins will be needed to access some features. And during development, bugs and build/distribution issues will creep up. Any of these things can happen and will require deep platform specific knowledge. For good developers, language is mainly about syntax, but good platform knowledge is much more than just syntax. It’s understanding the various capabilities of each platform, their restrictions or limitations, and their UX paradigms.

In the End, We Choose Native

There are multiple options when it comes to building mobile applications.  Deciding on the proper path for your application is about more than just the line item cost of development.  Many considerations need to be assessed when determining the actual cost of development.  Ultimately you need a highly performant, beautifully designed mobile application for your users. My goal is to make sure your users have exactly that. Contact me to help you determine the right path.

UITableView Swipe Actions


One of the new but little discussed APIs in iOS 11 allows the addition of swipe actions on UITableView rows via the new UISwipeActionsConfiguration class and associated UITableViewDelegate methods. Adding swipe left or swipe right actions is now pretty simple, so lets just dive right in. To try out these new APIs, a very basic list view was created with some hard coded data. This app will allow the user to swipe right to make a row “read” or “unread” and swipe left to either “flag” a row, or “delete” the row from the list. The code for this post can be found here.


The UITableView delegate

The keys to adding swipe actions start with new UITableView delegate methods, defined as follows:

func tableView(UITableView,
              leadingSwipeActionsConfigurationForRowAt: IndexPath)
                                    -> UISwipeActionsConfiguration

func tableView(UITableView,
               trailingSwipeActionsConfigurationForRowAt: IndexPath)
                                    -> UISwipeActionsConfiguration

As you can see in the method signatures, these both return a UISwipeActionsConfiguration class. This class is initialized with an array of UIContextualAction classes. So let’s start at the bottom and work our way up.


The Details

For our sample app, we’ll create a struct called an Email. It looks like this:

struct Email {
    let subject: String
    let body: String
    var isNew: Bool
    var isFlagged: Bool

    static func mockData(numberOfItems count: Int) -> [Email] {
        var emails = [Email]()
        for idx in 1...count {
            let email = Email(subject: "Email \(idx)", body: "This is my body for email \(idx)", isNew: true, isFlagged: false)
        return emails

    mutating func toggleReadFlag() -> Bool {
        self.isNew = !self.isNew
        //normally make some call to toggle and return success/fail
        return true

    mutating func toggleFlaggedFlag() -> Bool {
        self.isFlagged = !self.isFlagged
        //normally make some call to toggle and return success/fail
        return true

We will use this class to load up the table view with data. This is accomplished using the typical UITableViewDataSource methods and can be seen within the ViewController class. The real area of interest is within the UITableViewDelegate. Here we introduce the 2 new methods mentioned above.


Setting up the UISwipeActionsConfiguration

Let’s take a deeper dive into the trailing actions method, since it will apply more than one possible swipe action.

func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
        let deleteAction = self.contextualDeleteAction(forRowAtIndexPath: indexPath)
        let flagAction = self.contextualToggleFlagAction(forRowAtIndexPath: indexPath)
        let swipeConfig = UISwipeActionsConfiguration(actions: [deleteAction, flagAction])
        return swipeConfig

Here, we are using a helper method to instantiate each of the UIContextualAction classes we will need to build our swipe actions. Then we can instantiate a UISwipeActionsConfiguration using the UIContextualAction classes to populate the actions array. The UISwipeActionsConfiguration is then returned from the delegate method.

The important thing to note here, is that the order of the items in the action array determines the order of the actions displayed when the table view row is swiped. The easiest way to remember is that the first item displays furtherest out, and subsequent items display moving towards the cell. So if we are dealing with trailing actions, the first item in the array corresponds to the rightmost action (“Delete”), the second one will be one inside of that (“Flag”), and so on.


Handling Contextual Actions

Next, lets take a look at the UIContextualAction. This is where the work happens. The documentation found here. The initializer takes a UIContextualAction.Style, title, and UIContextualActionHandler block. The UIContextualActionHandler gives you access to the UIContextualAction, the view that displayed the action, and a completion handler that you pass a bool indicating whether or not the action was successful. An example can be found in the contextualToggleFlagAction method shown below:

func contextualToggleFlagAction(forRowAtIndexPath indexPath: IndexPath) -> UIContextualAction {
        // 1
        var email = data[indexPath.row]
        // 2
        let action = UIContextualAction(style: .normal,
                                        title: "Flag") { (contextAction: UIContextualAction, sourceView: UIView, completionHandler: (Bool) -> Void) in
            // 3
            if email.toggleFlaggedFlag() {
                // 4
      [indexPath.row] = email
                self.tableView.reloadRows(at: [indexPath], with: .none)
                // 5
            } else {
                // 6
        // 7
        action.image = UIImage(named: "flag")
        action.backgroundColor = email.isFlagged ? UIColor.gray :
        return action

In this method:

  1. We are simply retrieving the data element from our data array
  2. Instantiating the UIContextualAction class, providing a style, title and handler
  3. Mutating the object. Of course our email struct could have been a class to ease the mutation handling.
  4. Saving the mutated object back to our data and reloading the appropriate rows.
  5. Call the provided completion handler, indicating success.
  6. Had the update to the object failed, we can indicate that to the completion handler by passing false.
  7. Setting the image and color attributes on action. By specifying an image, the title in the initializer is not displayed. This certainly makes localization a bit more work, since the images would need to contain any text we wanted to display for an action, assuming we wanted both text and images.

One more thing of note is that on the UISwipeActionsConfiguration class, you can specify whether the first action in the collection should be performed with a full swipe. This defaults to true. Here is a video of the working app with both leading and trailing swipe actions.

Changing your iOS App Icon programatically

When iOS 10.3 was released, Apple opened up an API to allow developers to change the app icon for their app. Of course this doesn’t mean you can change it every second like the Clock app, or even every day like the Calendar app. What you can do is change the app icon when the app is running in the foreground, and it will notify the user with a pretty ugly system alert dialog that the icon is changing. This post will walk through the configuration and API calls to allow an app to change the app icon.

The first step is to obtain your app icon image assets. These must be .png files and you will need 2x and 3x resolutions. An important thing to consider is that you want all the proper icon sizes available so that when the icon changes it is consistent across settings, spotlight, notifications, etc.

Unfortunately, these cannot be placed in a xcassets file, however, they must be packaged in the main bundle. The source code for this post can be found here.

The next step is to configure the Info.plist file. Review the documentation for the plist file carefully. In the provided code, the plist file contains the CFBundleIcons dictionary configured as show below:

Screen Shot 2017-07-13 at 9.19.42 AM

In the CFBundleAlternateIcons dictionary, the key represents the string that will be used when making the API call to change the app icon.  You will see these used in the code samples later in this post.  The value is an array of CFBundleIconFiles.  In our case, its an array of one item, with the relative path to the filename (without extension and size modifier).  If you like to keep your files organized in both Xcode and the filesystem like me, you’ll want to store your icons in a sub folder within your project, so it’s important to specify the relative path, otherwise you’ll get a runtime error when trying to change icons.

Now on to the code.  The API docs can be found here:  The APIs are pretty basic.  Ideally you want to check if the app can change the app icon with something like the following:

if UIApplication.shared.supportsAlternateIcons {
    print("I can do it")

Then to change the icon, do something like this:

//note that the name corresponds to the key in the 
//  Info.plist CFBundleAlternateIcons dictionary
UIApplication.shared.setAlternateIconName("hockey") { (error: Error?) in
    guard let error = error else {
    print("switching icon to hockey encountered and error: \(error)")

Finally, to reset the icon back to the primary one by setting the name to nil:

UIApplication.shared.setAlternateIconName(nil) { (error: Error?) in
    guard let error = error else {
    print("switching icon to primary encountered and error: \(error)")

Simple as that. Check out the sample app and switch icons between your favorite Philadelphia sports teams 😃

Using Node.js and Charles Proxy to Mock a Server API

While working on an iPhone project for a client, I came across a situation where I needed to test some error conditions returned from a server API which I have no control over.  I ended up using Charles Proxy to remote map the server API calls to a locally running Node.js server.  Of course the proper way to do this is to write functional tests and mock the networking classes to return the appropriate responses, but that is a blog post for another day.

In this post, I’ll walk through the steps to create a simple iPhone app that interacts with a public API, using Node and Charles to simulate an error response.  This post assumes some experience writing iOS code, but all the source code will be available at

Create an iOS App

For the iOS app, I’ll write a simple weather app that uses the OpenWeatherMap API.  We all know the world needs yet another weather app :).

Let’s start by creating a new single view project in Xcode.  In my iOS projects I almost always use CocoaPods for dependency management.  CocoaPods makes it easy to add/remove 3rd party libraries to your iOS project.  In this app, we’ll use AFNetworking to access the API, and I’ll add MBProgressHUD in case the response time is slow and the user needs to wait for UI updates. The following assumes that you already have CocoaPods installed.

After creating the Xcode project, quit Xcode (or close the project) and create a text file named “Podfile” at the root of the project.  The contents should include the following:

platform :ios, '7.0'

pod 'AFNetworking', '~> 2.0.3'
pod 'MBProgressHUD', '~> 0.8'

With that file in place, drop to a command line and execute pod install

That will create a workspace and configure the libraries. From this point forward, we use the workspace instead of the project. The final version of the application will look like this:


The code base can be found at, but the key portion is the API call, which is below (without all the details)

[[CSMServerAPI sharedInstance] weatherForLongitude:-75.1914 
    successBlock:^(NSDictionary *weatherDict) {
        // code to map API response to UI elements here
    } failureBlock:^(NSError *error) {
        //access error message parts from response here
        NSString *msg = ...
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Houston - We have a Problem" 
        [alert show];

If everything is successful, the UI gets populated with the weather data. But, if there is a failure, we throw an alert up to the user containing the error messages (I know, alerts are not user friendly, but this is an example).

Mocking an error with Node

Now that we have the API calls in place, we need to set up our node server to fake an error response. Sticking with the theme of keeping things simple, I used the express framework for node. With node installed, I created a directory for my server app and added a ‘package.json’ file inside. The ‘package.json’ looks like the following:

  "name": "mock-api",
  "description": "for use with charles proxy to mock error conditions for OpenWeatherMap API",
  "version": "0.0.1",
  "dependencies": {
    "express": "~3.4.7"

Dropping to a command line and executing npm install will set up the node server with the express module. Now we create an ‘app.js’ file and add our mock API, as follows

var express = require('express');
var app = express();

var errorJson = {error:"API Error",error_msg:"You have encountered an error thanks to Charles and Node....have a nice day!"};

app.get('/weather', function(req, res) {
  	res.json(400, errorJson);

app.listen(process.env.PORT || 4730);

Since our call to the OpenWeatherMap API is a get request to the /weather URI, we simply handle that request route in our code and return the response we want, which is an error containing a JSON error message. To start the server, execute node app.js at the command line and the server will be listening on port 4730.

Configure Charles Proxy for Remote Mapping

If you code against server APIs and don’t use Charles Proxy, or something like it, you really should start. It is immensely valuable for troubleshooting API calls, and the more I use it, the more nice features I find. I’ve used it for bandwidth throttling, request/response inspection, breakpoints (to change requests or responses), and now URL mapping. In order to map the OpenWeatherMap API to our local node server, access the Map Remote settings via the Tools -> Map Remote... menu. Once there, add a new remote mapping, filling out the fields as shown below. The configuration was also exported and is available at


With that in place, enable remote mapping, run the iPhone app and get the following error:


If you used Charles to record your network requests, you can even see the mapping occurred in the request overview notes. That’s all there is too it. You can certainly do a lot more than just simulate errors with this set up. I’ve used it to simulate server application errors as well, where server returns an http 200, but the response includes some application specific errors. Timeouts can be tested as well using the connect-timeout module. There is an example in the source code for that too.

So this is one way to intercept your API calls and modify them for testing. This is certainly no replacement for good functional tests, but simply another thing to add to your developer toolbox.

Securing Data in iOS Apps

There are numerous ways to secure data that you are storing on an iOS device.

The Simple/Built-in Way

The simplest way is to take advantage of iOS Data Protection (iOS 4+). This is accomplished by setting an attribute on a file like this:

    [[NSFileManager defaultManager] createFileAtPath:[self filePath]
                    contents:[@"super secret file contents" dataUsingEncoding:NSUTF8StringEncoding]
                    attributes:[NSDictionary dictionaryWithObject:NSFileProtectionComplete

There are several different levels of file protection. The following is taken from the NSFileManager class reference from Apple:

  • NSFileProtectionNone – no file protection
  • NSFileProtectionComplete – file is encrypted when the device is locked or booting
  • NSFileProtectionCompleteUnlessOpen – file is encrypted and can only be opened when the device is unlocked. Once open, the file can continue to accessed even if the user locks the device.
  • NSFileProtectionCompleteUntilFirstUserAuthentication – The file is stored in an encrypted format on disk and cannot be accessed until after the device has booted. After the user unlocks the device for the first time, your application can access the file and continue to access it even if the user subsequently locks the device.

A Core Data sqlite store can also be encrypted by setting the NSFileProtectionKey file attribute to one of the above values (after you create your persistent store coordinator).

However, an important thing to realize is that this type of data protection requires the device to have a passcode set on it (


What if you really need to insure that your data is protected regardless of whether the device has a passcode set? One way is to use the CommonCrypto libraries from Apple. This can be fairly complex. There is a great write up here from Rob Napier on what’s involved. Fortunately, he has also provided a wrapper that greatly simplifies this process here. Using this library (or writing your own), you can encrypt your data and store it wherever you need. If you are using Core Data, you could write an NSValueTransformer for the Core Data entity attributes that require encryption using CommonCrypto or the RNCrypto library to encrypt/decrypt the attribute values when accessing or updating them.


One more way to protect your data, specifically data that you want to store in a SQLite database, would be to use SQLCipher. SQLCipher encrypts/decrypts data at the page level and is transparent to your application code. You still use the standard SQLite APIs, with one additional method call when accessing the database (passing your key to sqlite). There are excellent instructions on setting it up for use in an iOS project here.

You can build SQLCipher as a set of static libraries by following the same iOS instructions with some modifications and additions. Here are the high level steps:

  1. Instead of creating a view based iOS project, create a static library project
  2. Follow the balance of the steps for including SQLCipher in your project
  3. Add a new “Aggregate” build target
  4. Add a “Run Script” build phase and paste the following script into it. This will build both the simulator and iOS based targets for the libcrypto, libsqlcipher, and libssl libraries.
  5. xcodebuild -project ${PROJECT_NAME}.xcodeproj -sdk iphonesimulator -target ${PROJECT_NAME} -configuration ${CONFIGURATION} clean build CONFIGURATION_BUILD_DIR=${BUILD_DIR}/${CONFIGURATION}-iphonesimulator
    xcodebuild -project ${PROJECT_NAME}.xcodeproj -sdk iphoneos -target ${PROJECT_NAME} -configuration ${CONFIGURATION} clean build CONFIGURATION_BUILD_DIR=${BUILD_DIR}/${CONFIGURATION}-iphoneos
  6. Add another “Run Script” build phase and paste the following script into it. This will merge the simulator and iOS builds into one for each library. These three libraries are what would be added to a project using SQLCipher.
  7. CRYPTO_LIB="${BUILD_DIR}/${CONFIGURATION}-iphonesimulator/libcrypto.a" &&
    SQLCIPHER_LIB="${BUILD_DIR}/${CONFIGURATION}-iphonesimulator/libsqlcipher.a" &&
    SSL_LIB="${BUILD_DIR}/${CONFIGURATION}-iphonesimulator/libssl.a" &&
    DEVICE_CRYPTO_LIB="${BUILD_DIR}/${CONFIGURATION}-iphoneos/libcrypto.a" &&
    DEVICE_SQLCIPHER_LIB="${BUILD_DIR}/${CONFIGURATION}-iphoneos/libsqlcipher.a" &&
    DEVICE_SSL_LIB="${BUILD_DIR}/${CONFIGURATION}-iphoneos/libssl.a" &&
    # Create framework directory structure.
    rm -rf "${UNIVERSAL_LIBRARY_DIR}" &&
    mkdir -p "${UNIVERSAL_LIBRARY_DIR}" &&
    # Generate universal binary for the device and simulator.
    lipo "${CRYPTO_LIB}" "${DEVICE_CRYPTO_LIB}" -create -output "${UNIVERSAL_LIBRARY_DIR}/libcrypto" &&
    lipo "${SQLCIPHER_LIB}" "${DEVICE_SQLCIPHER_LIB}" -create -output "${UNIVERSAL_LIBRARY_DIR}/libsqlcipher" &&
    lipo "${SSL_LIB}" "${DEVICE_SSL_LIB}" -create -output "${UNIVERSAL_LIBRARY_DIR}/libssl"

Once completed, you can build your new aggregate target and there should be 3 libraries located in a subdirectory within your project build directory. Just add these to your XCode project as you would any other library and you are good to go.

I have also posted this article on my companies blog, located here.

Using JQuery Mobile, Backbone.js for Handling Forms


In this post, I continue the development of my basic “exercise app” that I started (and enhanced) in these posts:

Let’s add the ability to create and edit exercise records.

Adding a new activity

Just like in the earlier post, the first thing we need is a jQueryMobile page to hold the form content. Add the following to index.html:

    <div data-role="page" id="activity-form" data-add-back-btn="true">
      <div data-role="header">
        <a href="#" data-role="button" data-icon="check" data-theme="b" data-rel="back" id="save-activity-button" class="ui-btn-right">Save</a>
        <h1>New Activity</h1>
      <div data-role="content" id="activity-form-content">
          <!-- the contents of the form will be rendered via the backbone view -->
          <form id="activity-form-form" action="#"></form>

In the code above, we see the typical jQueryMobile page. The main things of interest here are with respect to the anchor tag in the header div:

  • Specify data-rel=”back” to navigate to the previous page once the save is complete. This way whether we enter the form page from “Add” or “Edit”, navigation will be handled.
  • The class=”ui-btn-right” moves the button to the right side of the header bar.
  • The data-theme=”b” causes the save button to use the blue theme.

The next step is to define the template that the view will use to render the content for this page. Lets start with a simple template with an input for each attribute of an activity. To vary the UI slightly, we can use a drop down for the activity type. The basic template will look like this:

    <script type="text/template" id="activity-form-template">
        <label for="date" class="select">Date</label>
        <input type="date" name="date" id="date" placeholder="Date" value="<%= date %>" />
        <label for="type" class="select">Type</label>
        <select name="type" id="type">
        <label for="distance">Distance</label>
        <input type="text" name="distance" id="distance" placeholder="" value="<%= distance %>" />
        <label for="minutes">Minutes</label>
        <input type="tel" name="minutes" id="minutes" placeholder="" value="<%= minutes %>" />
        <div data-role="fieldcontain">
            <textarea name="comments" id="comments" placeholder="Comments"><%= comments %></textarea>

Notice that we are using the HTML 5 input types for some of the fields. Browser support for these will vary, but worst case they will deprecate to a text input type. For example, on iOS, the date will present a native date picker, whereas on Android (or Chrome, etc.) the field will behave as a standard text input.

Now we need to navigate to the form page. This requires modifying the “Add” button on the list page.

    <div data-role="page" id="activities">
      <div data-role="header">
        <a href="#activity-form" data-role="button" data-icon="add" id="add-button" class="ui-btn-right">Add</a>
      <div data-role="content">
          <!-- the contents of the list view will be rendered via the backbone view -->

In order to transition to the form page, the href attribute on the anchor tag (i.e. button) needs to be changed to the id of the form page, as shown in line 4 above. The final step in presenting the form page to support adding exercise activities is modifying the add button click handler.

    $('#add-button').live('click', function(){
        var activity = new exercise.Activity(),
            activityForm = $('#activity-form-form'),

        activityFormView = new exercise.ActivityFormView({model: activity, viewContainer: activityForm});

Here we create an empty model, grab the form node, create a new exercise.ActivityFormView with these objects, and render the form. Testing at this point reveals a problem. The screen shot below doesn’t look right 😉

Investigating the browsers console reveals an error: Uncaught ReferenceError: distance is not defined. This is due to the underscore template trying to access an undefined attribute of the model. The issue is described here with some work arounds. I found the easiest workaround is to provide defaults for the model, as shown below.

     exercise.Activity = Backbone.Model.extend({
        defaults: {
            date: '',
            type: '',
            distance: '',
            comments: '',
            minutes: ''

Now the form renders properly. With the help of some CSS, we can tighten things up a little and end up with the version on the right (the CSS is part of the source code, see the links at the end of this post).

Editing an existing activity

With the template and the view already implemented, adding edit functionality is pretty straightforward. The first step is to update the href attribute of the edit button on the activity-details page.

    <div data-role="page" id="activity-details" data-add-back-btn="true">
      <div data-role="header">
        <a href="#activity-form" data-role="button" data-icon="arrow-d" id="edit-activity-button" class="ui-btn-right">Edit</a>
        <h1>Activity Details</h1>
      <div data-role="content" id="activity-details-content">
          <!-- the contents of the list view will be rendered via the backbone view -->

As we did with the add button, this should reference the activity-form page. Now we need to add the click event handler for the edit button.

    $('#edit-activity-button').live('click', function() {
        var activityId = $('#activity-details').jqmData('activityId'),
            activityModel = exercise.activities.get(activityId),
            activityForm = $('#activity-form-form'),
        activityFormView = new exercise.ActivityFormView({model: activityModel, viewContainer: activityForm});

If you recall, the activityId is passed to the details page view the list item click event handler. We reuse that fact here to retrieve the activity from the collection.

Time to test. Selecting an activity renders the detail page. Clicking the edit button renders the form, pre-filled with the activity details. Everything looks great.

But wait…..that screenshot was from the browser on which I am testing. We should always test on devices as well. Earlier I mentioned that we are using some of the HTML 5 input types (i.e. date). The nice thing is that iOS 5 will render a nice date picker for date types. The challenge is that the date needs to be in a specific format for that to work. The image below shows what the form page looks like on an iOS device.

Fixing the Date

No date value is showing up on our iOS device. This is a known issue. So, for iOS we need the date format as yyyy-mm-dd, while for other platforms, I prefer the date to be shown as mm/dd/yyyy. I do realize that date formats should be localized, but for the purpose of this example I would like to keep it straightforward and specify mm/dd/yyyy as the display date format. There are many options that could be pursued here, but to demonstrate some more capabilities of Backbone.js, we will modify our model to help meet our date requirements.

First, the date attribute in our JSON feed is a string. Lets convert this to a date when the data is retrieved from the server, then when we need the date, we can just manipulate it as needed. This can be accomplished several ways.

  • Implement a parse method on the collection that converts the String to a Date as the data is being fetched from the server.
  • Implement a method on the model that converts the date String to a Date and sets it on the model. This would then require the calling code to know to call this method depending upon the circumstance.
  • Override the set method on the model, look for the date attribute, then convert it to a date as needed.

The last option is the most seamless approach. Add the following method to the Activity model.

        set: function(attributes, options) {
            var aDate;
            if ({
                //TODO future version - make sure date is valid format during input
                aDate = new Date(;
                if ( === "[object Date]" && !isNaN(aDate.getTime()) ){
           = aDate;
  , attributes, options);

Also, update the defaults so that the date attribute is now a Date instead of a String.

        defaults: {
            date: new Date(),
            type: '',
            distance: '',
            comments: '',
            minutes: ''

While this clearly isn’t the most robust date handling, it is fine for now. In a future version, this should be improved.

Next, add attributes to our model that will format the date in the ways we need it (i.e. mm/dd/yyyy and yyyy-mm-dd).

        dateInputType: function(){
            return exercise.formatDate(this.get('date'), "yyyy-mm-dd"); //
        displayDate: function(){
            return exercise.formatDate(this.get('date'), "mm/dd/yyyy");

The formatDate function is a simple date formatter to meet our specific needs and can be found in the source code that accompanied this post (see link at the bottom of the post).

Now, how do we use these new methods in our view. The first thing to realize is that we pass the template JSON. The default implementation of the toJSON method of a Backbone.js model will not include these functions. Therefore, we need to override the toJSON method.

        toJSON: function(){
            var json =;
            return _.extend(json, {dateInputType : this.dateInputType(), displayDate: this.displayDate()});

Here, we are using the Underscore.js extend to add our attributes to the standard Backbone JSON. Now, we need to modify our view templates to use the appropriate JSON attributes.

    <script type="text/template" id="activity-list-item-template">    
      <li><a href="#activity-details" identifier="<%= id %>"><%= displayDate %> - <%= type %></a></li>
    <script type="text/template" id="activity-details-template">
        <h3><%= type %></h3>
        <ul data-role="listview" id="activitiy-fields" data-inset="true">
          <li>Date: <%= displayDate %></li>
          <li>Minutes: <%= minutes %></li>
          <li>Distance: <%= distance %></li>
          <li>Comments: <%= comments %></li>
    <script type="text/template" id="activity-form-template">
        <label for="date" class="select">Date</label>
        <% if (navigator.userAgent.indexOf('iPhone') >= 0 || navigator.userAgent.indexOf('iPad') >= 0) { %>
            <input type="date" name="date" id="date" placeholder="Date" value="<%= dateInputType %>" />
        <% }else{ %>
            <input type="date" name="date" id="date" placeholder="Date" value="<%= displayDate %>" />
        <% } %>
        <label for="type" class="select">Type</label>
        <select name="type" id="type">
        <label for="distance">Distance</label>
        <input type="text" name="distance" id="distance" placeholder="" value="<%= distance %>" />
        <label for="minutes">Minutes</label>
        <input type="tel" name="minutes" id="minutes" placeholder="" value="<%= minutes %>" />
        <div data-role="fieldcontain">
            <textarea name="comments" id="comments" placeholder="Comments"><%= comments %></textarea>

Notice that lines 16-21 include some conditional logic. This is a very basic device detection check to determine which date format to use. There are plug-ins,etc. that provide more robust alternatives, but to keep things clear, this will serve our needs. The screen shots below show the desktop browser and the iOS versions of the form with the appropriate date handling.


The final step is to implement the save functionality.

    $('#save-activity-button').live('click', function(){
        var activityId = $('#activity-details').jqmData('activityId'),
            formJSON = $('#activity-form-form').formParams();
        //if we are on iOS and we have a date...convert it from yyyy-mm-dd back to mm/dd/yyyy
        //TODO future version - for non-iOS, we would need to validate the date is in the expected format (mm/dd/yyyy)
        if ( && ((navigator.userAgent.indexOf('iPhone') >= 0 || navigator.userAgent.indexOf('iPad') >= 0)) ){
            dateComponents ="-");
   = dateComponents[1] + "/" + dateComponents[2] + "/" + dateComponents[0];
        if (activityId){
            activity = exercise.activities.get(activityId);
            activity.set(formJSON); //not calling save since we have no REST in memory
            //new (since we have no REST backend, create a new model and add to collection to prevent Backbone making REST calls)
            activity = new exercise.Activity(formJSON);
            activity.set({'id': new Date().getTime()});  //create some identifier

I used the JavascriptMVC formParams jQuery plugin (found here) to convert my HTML form into a JSON object. Then, the date is converted into the appropriate format. One thing to note here is that since we have no real back end server for Backbone to interface with, we don’t call save on the model or create on the collection. These methods would cause the appropriate REST calls to the server.

Since the click event on the list view passes the activityId to the details page, we can use this to determine if we are adding or editing. One thing to consider here is that the user may click an existing activity, then go back to the list, then click add. In this case, the activityId from the previously selected activity is still attached to the activity-details view. This will cause our save implementation to think we are editing. To prevent this, we should remove the activityId from the activity-details page when adding a new activity. This can be accomplished by adding the highlighted line below to the add handler.

    $('#add-button').live('click', function(){
        var activity = new exercise.Activity(),
            activityForm = $('#activity-form-form'),
        //clear any existing id attribute from the form page
        activityFormView = new exercise.ActivityFormView({model: activity, viewContainer: activityForm});

The final step is to make sure our views are updated accordingly when we add or modify activities. Since the details view retrieves the activity before the page loads, no change is required here. But our list view only renders during the initial page load. This is where we can take advantage of Backbone event binding. A few small additions to the ActivityListView and things will be handled.

        initialize: function() {
            this.collection.bind('add', this.render, this);
            this.collection.bind('change', this.changeItem, this);
            this.collection.bind('reset', this.render, this);
            this.template = _.template($('#activity-list-item-template').html());


        changeItem: function(item){

The change event will bubble up from the model and fires as a result of the set being called. In the changeItem method, we sort the collection to handle any changes in the date attribute. The sort method call will cause the reset event to fire, which then results in the render method invocation, causing the list to be re-rendered. This keeps everything in the correct order. The add event will be fired when we add a new activity to the collection. Since we implemented the comparator method on the collection, models added to the collection will be added in the appropriate order.

We can now add and edit activities. Start exercising 🙂

The source code for this post can be found here