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-list>
  <ion-item ng-repeat="item in items">
    Hello, {{item}}!
  </ion-item>
</ion-list>

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.

TemplateA.html

{{modelObject.name}}

TemplateB.html

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

HomeCtrl.js

.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.

Home.html

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

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.

ImageSubmissionCtrl

// 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
      coupleImageFileWithObject(result.name);
    })
    .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.

ClientOfApiService.h

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;

ClientOfApiService.m

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

        if (error)
        {
            completion(NO);
            return;
        }

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

        completion(success);
    }];
}

ApiService.h

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"

SPEC_BEGIN(ClientOfApiServiceSpec)

describe(@"ClientOfApiService", ^{
    
    // system under test (class being tested)
    __block ClientOfApiService *sut;
    __block id apiService;
    
    // Runs before each test
    beforeEach(^{
        sut = [[ClientOfApiService alloc] init];
        apiService = [KWMock mockForClass:[ApiService class]];
        
        // Inject the mocked apiService into the ClientOfApiService instance
        sut.apiService = apiService;
    });
    
    // Runs after each test
    afterEach(^{
        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
        beforeEach(^{
            
            // 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)];
            }];
        });
        
    });
});

SPEC_END

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
        ...
    }
}

Ta-da.

Tidbits

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:


#server-side

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:

Screenshot_2013-07-05-13-17-49

Phone portrait

device-2013-07-04-183752

Tablet landscape

device-2013-07-04-183939

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 :/