Tag Archives: iOS

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(), {
      self.getJsonData()
   })
}

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: {
         data, 
         response, 
         error -> Void in
         
            println("Task completed")
           
            if(error != nil) {
                println(error.localizedDescription)
            }
            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")
            }
        })
        
   task.resume()
}

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.

Advertisements

Fixing jQuery Mobile headers in a Worklight app on iOS 7

One of the fun bits (depending on your inclination) of working cross-platform is discovering and mitigating the nuanced differences as you try your app on different devices. One such difference in iOS 7 is the transparency of the iOS status bar that contains the wifi strength, battery life and so on.

iOS header area

If you’re not including a header in your app then this won’t make a whole lot of difference to you, but if you are, you’ll find the iOS status bar overlays your header which can mess up your carefully placed buttons, iconography and header text.

I’ve come up with a simple workaround for jQuery Mobile running in a Worklight environment that I’ve posted here for ease of reuse and in case anybody else is looking for similar. The same principle should apply equally in a vanilla Cordova app too.

My example uses a simple jQuery Mobile header on a page.

<div data-role="page" id="mypage">
   <div data-role="header" data-position="fixed" 
      data-fullscreen="false">
      <a href="#home" 
class="ui-btn ui-icon-back ui-btn-icon-notext ui-corner-all"
>Back</a>
      <h1>My heading</h1>
   </div>
   <div data-role="main" class="ui-content">
      Blah blah
   </div>
</div>

The overlap of the status bar is 20 points, so when the app renders we need to first detect whether we’re on a version of iOS that needs adjusting, then fix the elements contained in the header to allow for the status bar height.
For the purposes of demonstration I’ve simplified the below just to test for the iOS version assuming an Apple device, but of course you can add further tests for other platforms.

<head>
//... head contents
<script>
function onDeviceReady() {
   if (parseFloat(window.device.version) >= 7.0) {
      $('H1').each(function() {
         // `this` is the h1, the padding goes on the
         // containing header div.
         $(this).parent().css("padding-top", "20px");
         // sort any buttons/icons rendered from A tags too
         $(this).siblings('A').css("margin-top", "20px");
      });
   }
}
// Fire when Cordova is up and ready
document.addEventListener("deviceready", 
                           onDeviceReady, false);
</script>
//... rest of head contents
</head>

The logic of script searches for h1 tags on the assumption that they will be used for header text. If your interface is styled differently, you might want to come up with a different “eye-catcher” tag or attribute so jQuery can select all the nodes for the headers in the app. Having found the h1 tags, it then adjusts the containing div nodes to pad out from the top by the required amount. My application has a tags for buttons in the header, which a bit of experimentation showed were not being adjusted along with the containing div, so I’ve adjusted them directly.

Notice that I’ve used CSS padding for the h1 – this means that the additional offsetting will be filled with the natural background scheme of the header, rather than a blank white oblong which would occur if margin were used. The jQuery icons for my back link get distorted by tinkering with the padding, so I’ve used margin which works just fine as they layer over the top of the heading colour scheme.