Tag Archives: mobile

Calling a REST service from Swift — a quick example

I figured this would be a recurring theme, so thought I’d write it down for posterity, not least so I didn’t lose it. The scenario is a common one — we have a mobile app for iOS written in Swift where in response to some kind of user trigger we need to go off to the server to do some work via a REST endpoint using JSON as our protocol format. Here’s a snippet I created to do exactly this, a variation on a couple of similar examples but with a couple of notes of things I found along the way.

Let’s assume we’re in a simple View Controller where we’re responding to stimulus from the user in the form of a button. I have an action handler called getData to respond to a button push.

@IBAction func getData(sender: AnyObject) {
   dispatch_async(dispatch_get_main_queue(), {

You will notice a couple of things. Firstly we’re calling a another function on the controller that will actually do the heavy lifting. I’ve separated that out purely to make things easier to read and follow. The second thing is that I’m using the Grand Central Dispatch mechanism in Swift to spin off the action into a separate thread. This follows general good practice for user interface that you shouldn’t do work on the main thread that might block for some period of time, such as writing to the network or disk. Doing so could cause your app to hang and potentially be shut down by iOS as being unresponsive as a result (Apple themselves explain this nicely).

So now to the main guts of the code. In my simple case here I’m doing an HTTP GET of a JSON feed that returns an array of items that looks a bit like this:

    "device": "TEST",
    "event": "Testing",
    "date": "2014-08-12T08:31:25.449Z",
    "_id": "53e9d0ddf5d6a92100b8254c"
    "device": "TEST",
    "event": "Testing2again",
    "date": "2014-08-12T09:25:25.062Z",
    "_id": "53e9dd85f5d6a92100b8254d"

Here’s the function that does the work of going off to the server to get the feed.

func getJsonData() {
   var urlPath = "http://myserver/myaudits"
   var url = NSURL(string: urlPath)
   var session = NSURLSession.sharedSession()
   var task = session.dataTaskWithURL(url!, 
      completionHandler: {
         error -> Void in
            println("Task completed")
            if(error != nil) {
            var err: NSError?
            var results = NSJSONSerialization.JSONObjectWithData(data, 
               options: NSJSONReadingOptions.MutableContainers, 
               error: &err) as NSArray
            if(err != nil) {
                println("JSON Error \(err!.localizedDescription)")

            println("\(results.count) JSON rows returned and parsed into an array")
            if (results.count != 0) {
                // For this example just spit out the first item "event" entry
                var rowData: NSDictionary = results[0] as NSDictionary
                var deviceValue = rowData["device"] as String;
                println("Got \(deviceValue) out")
            } else {
                println("No rows returned")

Note that I’m explicitly casting the parsed JSON as an NSArray. One thing I discovered is that Swift isn’t massively tolerant if you get this wrong, for example if the JSON resolves to an Object, then you need to cast to an NSDictionary. Rather than return a useful message, it simply crashed the app. Now of course this was due to a genuine developer gaffe, but still it soaked up a fair amount of time trying to work out what was wrong.

With that, you should be all set. Hope this is useful.

Mobile web frameworks, and other religious debates

It is an interesting litmus test of the maturity of any given technology trend as to when it starts to develop its own set of heated points of debate and argument. We had the “browser wars” of the late ‘90s, and then proprietary plug-ins versus AJAX/open web and more recently which AJAX framework is “best”.

The rise of mobile apps as a party that everyone wants to be at has further amplified this frameworks debate, as the focus has evolved from AJAX on the desktop to the mobile platforms. A quick Google and you’ll find any number of fora debating the merits of jQuery Mobile vs Dojo Mobile vs Sencha Touch and so on.

So there are several, which one is best then?

In fact participation in such debate in isolation is ultimately futile. That a particular topic becomes the subject of almost religious fervour in itself betrays that absolute truth either is either very hard or impossible to prove. They key to finding an answer is understanding the context. What is best for one situation may not be best for another, and to suggest otherwise would do the asker of the question a disservice, assuming they are asking for help.

There are a number of considerations though that can help navigate to what best might be.

You’re at the mercy of consumers

Technical debate is all fine and good, but in the mobile world, we know that consumers will decide the success or failure of the app. A poor experience by the end user will ultimately be its undoing. The framework must be able to meet the experience expected by the users. This is of course a key factor in determining whether a native or mobile web/hybrid approach is applicable in the first place, but that is another discussion entirely.

Don’t forget also that user experience and aesthetics are two different things – nice transitions or shading will never rectify a fundamentally flawed user experience. Rejecting a framework purely because it apparently contains less bundled eye candy than alternatives still may not mean you’ve chosen wisely.

A green field is increasingly rare

Even in the evolving world of mobile, it is increasingly likely that there will be some existing apps with which the new apps will have to live happily. A few things to consider might be:

  1. Is there already an incumbent framework?
  2. Is the existing framework capable of building what is required to the right quality in the given timescales?
  3. Are the developers effective using it?

If the answer to the above is a clean sweep of “Yes”, then unless there is a non-technical reason why the existing framework should be abandoned,then that probably suggests that sticking with what is there is the best option.

A hygiene factor for any technology decision, but an important consideration is the current position in the “marketplace” of a given framework. Is the framework under consideration acknowledged by other developers (and vendors) as strategic, or are references thin on the ground?

Skills matter

The accelerated lifecycle of the mobile world means that development time is at a premium. Adopting a framework or approach that is a closer match to the skills available within the organisation means greater opportunity for reuse both of assets and skills, and shortens the time required for developers to get up to speed. Related to the previous consideration, if there is an incumbent framework and the decision is made to replace it then selecting a replacement with some similar characteristics would make sense – e.g. script-centric vs markup centric.

It’s still a browser

The growth of AJAX as a technique in general has placed far greater expectation on the browser environment in terms of its criticality to the delivery of the application. It is easy to forget that for all the enhancement and development since the birth of the internet, fundamentally a browser renders documents, and Javascript is there to augment that core purpose. I’ve always been fairly sceptical of attempting to layer on more tiers of engineering into the browser than are absolutely necessary.

So when looking at the various frameworks,  it should be borne in mind that it’s not necessarily the same as a package selection exercise with enterprise software products. Looking at one framework for the UI, another for handling MVC, another for service invocation and so on may well be overcomplicating things unless that specific combination is absolutely the only way to deliver the experience. It is relatively straightforward, for example, to create a simple MVC framework within most mobile frameworks without introducing the complexity and bloat of yet another framework.

Horses for courses

And finally a variation on the consultant’s answer of “it depends”, but it is certainly true that choosing the right framework depends on what you want to do with it.

For example, I like prototyping using jQuery for its lightweight CSS/HTML-centric approach, whereas for construction of reusable components in an enterprise app I can see where the Dojo Toolkit with its Java-like packaging and widget framework has its strengths. That’s not to say you can’t prototype that way in Dojo or indeed create widgets in jQuery, just they each have different strengths depending on the use for me personally. So a key consideration here when evaluating a framework is determining what its core use is going to be – for example, do you need to make a strategic decision for a new service or are you looking to put something disposable together quickly? In the latter case, depending on skill levels some may choose not to use a framework at all.