Dynamic List Items in an Ionic/AngularJS App

In an Ionic/AngularJS app when one wants to display a list of model objects, the following will typically be used:

  <ion-item ng-repeat="item in items">
    Hello, {{item}}!

In an app I’m currently working on, however, I wanted to make use of different items in a list dynamically, with the appearance of each item depending on various properties of the given model object in the list. I’d imagine that to solve this problem there are various ways of doing so, but I ended up using html view templates and the ng-include directive to achieve this. Below is a step-by-step walkthrough of the method I used:

  • Define HTML view templates for the different list items to be displayed.




<img class="full-image" ng-src="{{modelObject.image.url}}">
  • Add functions in the controller to determine the correct class & view template to use based on properties of the provided model object.


.controller('HomeCtrl', function($scope) {
  var vm = $scope;

  // Determines the correct CSS class to use based
  // on properties of the provided model object
  vm.itemClass = function(modelObject) {
    if (modelObject.type == 0) {
      return "class-A";
    else {
      return "class-B"

  // Determines the correct html view template to use based
  // on properties of the provided model object
  vm.itemTemplate = function(modelObject) {
    if (modelObject.type == 0) {
      return "app/path_to_template/templateA.html";
    else {
      return "app/path_to_template/templateB.html";
  • Then in the view displaying the list, it’s as simple as referencing the relevant controller functions to dynamically determine the correct class and template to use for each item in the list at runtime.


      <ion-item ng-repeat="modelObject in modelObjects" ng-class="itemClass(modelObject)">
        <ng-include src="itemTemplate(modelObject)"></ng-include>

Uploading a base64 image to Parse with the REST API in AngularJS

Screen Shot 2015-05-31 at 8.34.44 PM

I was recently working on an Ionic/AngularJS app which needed to do the following:

– Upload a base64 image file (taken with the camera) to the Parse servers using the REST API.

– Associate the uploaded image file with an object and save the object to Parse using the REST API.


The Parse documentation didn’t seem to explain this specific case and other examples online seemed to all offer different details on how to get this done… so I ended up jumping through a few hoops until I eventually got it working. Below is an example of what I used to achieve this.


// camera is simply an injected service, wrapping the cordova APIs
.controller('ImageSubmissionCtrl', function($scope, $http, camera) {

  var vm = $scope;
  var imageData;

  // Object to save to Parse that includes an image
  var object = {
    text: "",
    image: null

  // Function to take a picture using the device camera
  vm.takePicture = function() {

    // Define various properties for getting an image using the camera
    var cameraOptions = {
      quality : 75,
      // This ensures the actual base64 data is returned, and not the file URI
      destinationType: Camera.DestinationType.DATA_URL,
      encodingType : Camera.EncodingType.JPEG

    // Use the Cordova Camera APIs to get a picture. For brevity, camera
    // is simply an injected service
    camera.getPicture(cameraOptions).then(function(returnedImageData) {
      imageData = returnedImageData;

    }, function(err) {
      console.log("Error taking picture: " + err);

  // Function to submit the object to Parse using the REST API
  vm.submitObject = function() {

    // This part is important. As part of the JSON that we send to Parse,
    // we need to specify the content type here as a field(__ContentType)
    // along with the image data. Notice that the Content-Type specified
    // in the headers is actually "plain/text"
    var dataToSubmit = {__ContentType : "image/jpeg", base64 : imageData};

    // First upload the image file
    $http.post("https://api.parse.com/1/files/image.jpg", dataToSubmit, {
           headers: {
               "X-Parse-Application-Id": PARSE_APP_ID,
               "X-Parse-REST-API-Key": PARSE_REST_API_KEY,
               "Content-Type": "plain/text"
    .success(function(result) {
      // Now associated the image file with the object
    .error(function(result) {
      console.log("Error uploading image file: " + err);

  // Function to associate the image file with an object and save the
  // object to Parse using the REST API
  function coupleImageFileWithObject(fileName) {

    // Assign the filename to our object prior to saving it to Parse
    object.image = {name : fileName, __type : "File"};

    // The 'ObjectClass' in the url should be replaced by the class name
    // of the object you are saving
    $http.post("https://api.parse.com/1/classes/ObjectClass", object, {
           headers: {
               "X-Parse-Application-Id": PARSE_APP_ID,
               "X-Parse-REST-API-Key": PARSE_REST_API_KEY
      .success(function(result) {
        console.log("Object successfully saved.");
      .error(function(result) {
        console.log("Error coupling image file with object: " + err);

It’s important to understand that the first step is to upload the file to Parse independently of the containing object, and then only on a successful response associate the file handle with the object and save the object itself to Parse.


Stubbing a method using a completion block in an iOS Kiwi test case

Kiwi is a great BDD (Behaviour-driven development) testing framework for iOS. The structure of a Kiwi test case involves specifying expected outcomes and behaviours for a given context or situation. The emphasis is on testing the “what” not the “how”.

I’ve been using Kiwi a fair bit recently, when I ran into a situation I wanted to test that wasn’t as clearly documented as I would’ve liked, so I thought I’d provide the solution I used here. I felt it best to dive straight into some example code to better explain the situation:

Class being tested: ClientOfApiService

Method being tested: doSomeActionThatInvolvesApiService:

Class dependencies: ApiService

To properly test the behaviour of ClientOfApiService in isolation, we need to provide a mock of the dependency ApiService; failing to do this would mean relying on external behaviour which could potentially lead to inconsistent/invalid results.


typedef void(^ActionCompletionBlock)(BOOL success);

@class ApiService;

@interface ClientOfApiService : NSObject

@property(strong, nonatomic) ApiService *apiService;

 * Performs some action that requires the result of an API to indicate
 * success or failure.
-(void) doSomeActionThatInvolvesApiService:(ActionCompletionBlock) completion;


-(void) doSomeActionThatInvolvesApiService:(ActionCompletionBlock) completion;
    [self.apiService fetchTestNames:^(NSArray *testNames, NSError *error) {

        if (error)

        // Success is arbitrarily a name array of size 2
        BOOL success = (testNames != nil && [testNames count] == 2);



typedef void(^TestNamesCompletionBlock)(NSArray *testNames, NSError *error);

@interface ApiService : NSObject

 * Fetches some test names from the API and calls the specified completion
 * block when a result is received.
-(void) fetchTestNames:(TestNamesCompletionBlock) completion;

So, the objectives are:

  1. Stub the fetchTestNames method to use dummy data so that it does not have to make a real API call.
  2. On top of stubbing the fetchTestNames method call, we want the method to capture the TestNamesCompletionBlock parameter so that it can properly call back by executing the block with the dummy data.
  3. In our test case, verify that the outcome of the doSomeActionThatInvolvesApiService method is correct given the stubbed data used.

I’ll end this post with an example of a Kiwi test case that achieves the above objectives:

#import <Kiwi/Kiwi.h>
#import "ClientOfApiService.h"
#import "ApiService.h"


describe(@"ClientOfApiService", ^{
    // system under test (class being tested)
    __block ClientOfApiService *sut;
    __block id apiService;
    // Runs before each test
        sut = [[ClientOfApiService alloc] init];
        apiService = [KWMock mockForClass:[ApiService class]];
        // Inject the mocked apiService into the ClientOfApiService instance
        sut.apiService = apiService;
    // Runs after each test
        sut = nil;
        apiService = nil;
    it(@"ClientOfApiService instance should exist", ^{
        [sut shouldNotBeNil];
    // Given a particular context
    context(@"When testing doSomeActionThatInvolvesApiService with some dummy data", ^{
        // Runs before each test
            // OBJECTIVE 1. Stub the mocked ApiService to return an array of 2 names
            // We stub using a block so that we can capture that parameters passed to the
            // method we are stubbing. The parameters can be accessed in the params array
            // object
            [apiService stub:@selector(fetchTestNames:) withBlock:^id(NSArray *params) {
                // OBJECTIVE 2. Capture the TestNamesCompletionBlock parameter passed in so
                // that we can call back with the dummy data. The completion block parameter
                // is the only parameter of the method, so we access it at index 0.
                TestNamesCompletionBlock completionBlock = [params objectAtIndex:0];
                // Dummy data with 2 names
                NSArray *dummyArray = [NSArray arrayWithObjects:@"John", @"Matt", nil];
                // call back by executing the completion block parameter
                completionBlock(dummyArray, nil);
                // the test framework requires the block to return something
                return nil;
        // Verify that some condition is met. For test purposes,
        // success is abitrarily defined as the ApiService returning
        // exactly 2 names.
        it(@"should result in success being returned", ^{
            [sut doSomeActionThatInvolvesApiService:^(BOOL success) {
                // OBJECTIVE 3. verify that the correct result was returned
                // given the dummy data used.
                [[theValue(success) should] equal:theValue(YES)];


Authenticated Google Cloud Endpoint call from an iOS client

In my last post I mentioned the Google Cloud Endpoint framework which is a great way to produce an API that can be consumed across multiple platforms. Even though it is in preview release and subject to some teething problems, I highly recommend checking it out.

In a nutshell, the framework allows you to develop a backend and then generates the necessary data and proxy classes to use in your client projects to talk to the API. This means you no longer have to be concerned with the mechanics of making an API call, parsing the response data, etc., but can interface with the entire API through objects.

I’ve been playing around with the framework in bits and pieces and recently explored making an authenticated API call from an iOS client when I discovered a rather annoying issue: after successfully authenticating a user with OAuth 2, the local dev server would reject any subsequent API calls with the following error:

Cannot authorize request with scheme http

My iOS simulator and local dev server were just not getting along….

I knew that the problem was my local dev server was plain old http and that something, somewhere required https. After several attempts and the lack of any obvious info online, I started digging around the source code of the generated client classes…and, bingo!

The problem turned out to be that the iOS OAuth2 library would not authorize non-https requests, which meant I could not test authenticated calls locally. I eventually found a flag in the GTMOAuth2Authentication class of the iOS OAuth2 library which allows the library to authorize all requests (including non-https):

// Property indicating if this object will authorize plain http request
// (as well as any non-https requests.) Default is NO, only requests with the
// scheme https are authorized, since security may be compromised if tokens
// are sent over the wire using an unencrypted protocol like http.
@property (assign) BOOL shouldAuthorizeAllRequests;

By default this flag is set to NO. To update this flag to work with my outgoing requests, I changed its value in the OAUTH callback method prior to making any API requests:

- (void)viewController:(GTMOAuth2ViewControllerTouch *)viewController
      finishedWithAuth:(GTMOAuth2Authentication *)auth
                 error:(NSError *)error {
    [self dismissViewControllerAnimated:YES completion:nil];

    if (error != nil) {
        // Authentication failed
    } else {
        // Authentication succeeded

        // TODO: for development purposes only to use non-https....remove for release.
        auth.shouldAuthorizeAllRequests = YES;

        // Make some API calls



Just some interesting bits and pieces I have come across recently:

Flat UI Colors: a neat website that displays a colour palette, allowing you to click on a colour to copy its value to the clipboard. #design

ColorHex #android App: a simple colour picking app that that also allows one to store favourite colours. #design

Butter Knife: an interesting view injection framework for #android, created by Jake Wharton who also developed the ActionbarSherlock framework.

Latest Android Dashboard Stats: personally, I was surprised to see that as much as 9.9% of devices still fall under the small, ldpi configuration. #android

#programming #object-orientation

I recently did a bit of a refresh on some principles and guidelines for object orientated programming:


I spent a bit of time recently developing a simple REST web-service using Google go and Google App Engine. Here are some useful links and examples:

  • Gorca: a utility package for RESTful go applications on App Engine.
  • Home: a simple App Engine application using go and Angular JS.
  • RESTful web-services in go: useful information on developing RESTful web-services using Google go.

Anyone interested in developing web-service APIs that need to be consumed by mobile apps and the web, should definitely have a look at Google Cloud Endpoints… I also played around with this cool feature for Java and below are some useful links:

Webbits: a silly Android app for testing embedded web content.

Recently I found myself working with some server-side web content that would ultimately need to be pulled into an embedded browser within an Android app. Depending on the device, the embedded browser within the app could be of variable size, so the content being pulled would have to display properly.

I wanted a means to test the content within an embedded browser of different sizes, so I looked around (not for very long) for a test app that could help me out; after a little bit of looking and not finding what I wanted, I decided to just write my own silly app, called Webbits.

The app supports both phone and tablet and essentially allows a user to specify the dimensions of the embedded browser (WebView) and the URL to load. It’s very basic but did exactly what I needed. Below are some screenshots of Webbits:


Phone portrait


Tablet landscape


Developed by 2bits, of course.

Hopefully, someday, somebody else may find this useful.

Premature Optimization

I recently had a Java feature to implement which required some thought around read/write thread synchronization and performance. I don’t pretend to be expert on the topic of synchronization, and in fact, it’s an area of programming I have A LOT to learn about. It’s the kind of complex topic that often results in the panicky, overzealous and irrational behaviour you see in developers prior to yet another prematurely optimized solution being dumped on the world. When I approached this particular feature, I thought I wouldn’t fall into this trap. I was wrong.

The crux of the synchronization problem was that I wanted to be able to handle frequent concurrent read and writes to a Java ArrayList data structure in a thread-safe manner. It’s not that I didn’t know of a solution, but that I didn’t know of the best solution. After initially over-thinking the problem, I decided to post up on stackoverflow.com just to see how other developers out there with more experience on the subject would approach it. Fortunately, within minutes the community was already asking me questions in the comments that had me realise I never even had adequate data/info as to the load this feature would have to endure; yes, someday it may have to scale big time… but right now, it doesn’t!

Regardless of the process taken, I still managed to learn quite a bit about different synchronization techniques:

  • Collections.synchronizedList(): Automatically performs synchronization for single atomic operations (add, remove, get, etc.). Easy solution and likely suitable for most purposes.
  • CopyOnWriteArrayList: This results in a copy of the ArrayList being made each time it is modified to prevent exceptions when other threads are traversing the ArrayList. I couldn’t go with this option due to the high number of mutations required in the feature.
  • ReadWriteLock: Allows one to manually apply read & write locks to parts of the code requiring synchronization. The great thing with this solution is the ability to have thread-safe concurrent read operations, with the downside being more manual effort and synchronization code.

The funny thing is that as development of the feature continued, requirements changed and it turned out that having random access to the data wasn’t even necessary; as the only requirements needed were then traversals and mutations, the end solution changed to using the ConcurrentLinkedQueue data structure…..meaning all that initial over-thinking was, well, lame :/


Android WebView flicker when using hardware acceleration on Android 3.0+

There is an Android bug where WebViews may present an ugly flicker when being used on 3.0+ devices with Hardware Acceleration enabled. I was busy with an update to an Android app I’m working on which makes use of a WebView that slides in and out (using this awesome Sliding Menu library), when I noticed the *delightful* surprise when sliding the WebView back in:

Not ideal, is it?

Not ideal, is it?

As much as I can’t believe this kind of bug still exists, especially considering it seems to have been around for some time, it lives with us and thus we need to use some kind of workaround.  I immediately turned to SO for help and found a possible workaround:

WebView “flashing” with white background if hardware acceleration is enabled (Android 3.0+)

The workaround involves using a method that is only available from API level 11 (HoneyComb), and considering my app is targeting a minimum level of 8 I used the following code:

 * Initializes the WebView:
 * - Configures the WebView settings
 * - Adds a WebViewClient
 * - Custom config of the webview
private void initWebView()
	// Other init code
		// This is added as a work-around for the flicker which occurs in Android 3.0+
		// when hardware acceleration is enabled:
		// http://stackoverflow.com/questions/9476151/webview-flashing-with-white-background-if-hardware-acceleration-is-enabled-an
		getWebView().setLayerType(View.LAYER_TYPE_SOFTWARE, null);

So pick your poison: reduced performance or flickering?

The iOS BlocksKit framework is awesome…

iOS Blocks are segments of code that can be passed around for later execution, in the same manner as a value or parameter can be passed to a function. At first, the syntax surrounding the use of blocks may seem a little confusing or unconventional, but once you begin to use them, you will find that they are in fact relatively straightforward and can speed up your development in many instances.

void (^simpleBlock)(void) = ^{ ..... eh??!!?

void (^simpleBlock)(void) = ^{ ….. eh?!!?

The really great thing about Blocks is that they give you a quick way to define a snippet of code that can capture and access the enclosing scope and its values, yet still be executed at later point in time when a particular event has occurred; all of this without the hassle of having to define excessive delegates or callbacks.

BlocksKit is a really neat framework which consists of lots of utility and category classes to make the use of blocks more accessible with existing framework classes such as NSDictionary and UIBarButtonItem. Below is just one example of where BlocksKit can come in handy.

Example: Presenting a ModalViewController

Let’s take the example of presenting an information screen (InfoViewController) to a user in a universal application. On an iPad we may want to present the information screen as a popover without a navigation bar, however, on an iPhone we may want to present the screen modally but provide the user with a ‘Done’ bar button in the navigation bar to dismiss the screen; furthermore, let’s say we wanted to do this without having to alter the .xib of the InfoViewController.

One method of doing this would be to modify the InfoViewController’s implementation to add a ‘Done’ button only if executed on an iPhone, such as:

- (void)viewDidLoad
    [super viewDidLoad];

    BOOL iPhone = ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone);

    if (iPhone)
        UIBarButtonItem *doneButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(dismissViewController:)];
        self.navigationItem.rightBarButtonItem = doneButton;


This would result in a dismiss ‘Done’ button appearing in the navigation bar on an iPhone, but not when running on an iPad. Whilst this works, in some cases it’s not ideal that the InfoViewController itself has to be aware of how it is being presented, i.e. modally in this case; one would rather leave such logic to whatever is creating and using the view controller. Another (better) option would be to have the creator/user of the InfoViewController simply assign the navigation bar button itself and implement the button’s callback (selector) methods to dismiss the view controller. The downside here is having to implement unnecessary callback methods which clutter your class for such a simple purpose.

This is where blocks can come in really handy. For little tasks such as these, blocks containing the necessary operations to execute at a later stage can be defined and assigned in one place where it makes sense. Below is one example of how the above exercise can be implemented using BlocksKit:

    BOOL iPhone = ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone);

    InfoViewController *infoVC = [self.storyboard instantiateViewControllerWithIdentifier:@"InfoViewController"];

    if (iPhone)
        UINavigationController *modalController = [[UINavigationController alloc] initWithRootViewController:infoVC];

        // Present the view controller modally
        [self presentViewController:modalController animated:YES completion:^{

            // This block gets executed once the info view controller has finished presenting.

            // Create the done button for the navigation bar and implement the block that gets
            // executed when the button is tapped.
            UIBarButtonItem *doneBarButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone handler:^(id sender) {

                // When the button is tapped, dismiss the view controller
                [modalController dismissViewControllerAnimated:YES completion:nil];

            [infoVC.navigationItem setRightBarButtonItem:doneBarButton animated:YES];
        // Show as a popover view controller

And that’s it! Make sure to check out the BlocksKit framework for many useful classes that can make simple tasks quicker and cleaner IMO.

Simple Data Cache for iOS

I was searching for a simple cache to use for temporary storage of data from web-service calls when I came across EGOCache. Essentially I wanted something that provided the following features:

  • Simple key/value storage structure.
  • Time expiration of data.
  • Persistence of data in the cache.
  • Ability to easily store and persist custom objects.

So far EGOCache has worked really well for my purposes, and storing a custom object is as easy as implementing the NSCoding protocol on your object. The cache also provides an easy access mechanism to the global cache through the following call:

[EGOCache globalCache]

Although I recommend using the cache through a wrapper class; it will prevent coupling your code to the implementation and will safeguard your application code from changes to a different caching mechanism.