Category Archives: Programming

Anger Driven Development

As a programmer, it’s nice to imagine perfect productivity conditions: many well defined, small units of work lined up. If the work at hand is clear and you have ample time to get into a flow, you expect to finish many things. Unfortunately, real life rarely works out that way.

Instead of picturing an ideal, efficient scenario, I want to talk about a less than ideal productivity method that manages to pop up every now and then: Anger Driven Development (ADD). ADD in this context might mean different things to different people.

What ADD means to me is that I’m working on a task, get frustrated, and then refuse to be beaten. Some of my more productive times have occurred when I was so pissed at the situation that I refused to throw in the towel. I will NOT be beaten by a machine. The power of human will can be indomitable at times.

While driven to extreme frustration at what started off as an “easy task”, it becomes man versus machine. Man does not want to give up. Man refuses to give up.

Even if I was tired or had other reasons to put the work off until later, Anger Driven Development does not give me the choice to stop. Like taking a hammer to a screw and forcing it in through sheer will power and brute force, Anger Driven Development can be messy. Anger Driven Development can’t stop, won’t stop.

The most amazing part of ADD (besides the task that is now completed) is the sense of triumph at the end. While it always feels good to be productive and get things done, there are few things like the joy of victory after ADD.

Anger Driven Development would never be my modus operandi, but it inadvertently has its place in my toolbox.

WKInterfacePicker Attributes Illustrated

The WatchKit Framework’s WKInterfacePicker has some level of customization in Interface Builder.

As of this time of writing, there are 4 main attributes to configure:

  • Style
  • Focus
  • Indicator
  • Enabled

Style is the most important attribute since it heavily influences the type of Picker. The options for Style are List, Stack, and Sequence. List is the standard iOS-style 3d list of text. Stack allows you to flip through images as if it were a deck of cards. Sequence lets you move between images without any intermediate transition effect. For a good look, I’d recommend Big Nerd Ranch’s blog post.

Focus presents an outline around the currently focused/selected Picker. This is helpful if you have multiple WatchKit pickers or multiple elements for selection (think “Customize” for your watch face). The options are None, Outline, and Outline with Caption. The last option, “Outline with Caption”, comes into effect if your Style is Stack (or possibly Sequence), see an example here.

 

Plain, without focus

Plain, without focus

Left picker is focused

Left picker is focused

Indicator has two options: Disabled or Shown While Focused. The documentation wasn’t very clear: “A value indicating whether the picker uses an indicator to convey context about the number of picker items and which item is selected.” As far as I can tell, Disabled means the standard look, and the “Shown While Focused” adds a scroll bar helper on the right side of the watch.

Indicator - Shown While Focused

Indicator – Shown While Focused

Enabled is a helpful option that is either on or off. Enabling it or not doesn’t affect the view. When the picker is enabled, it allows the user to use the picker. This attribute can be set or unset programmatically with -setEnabled.

Hopefully this quick explanation of the different WKInterfacePicker attributes helps you out. The digital crown (AKA dial) & the WKInterfacePicker provides an extremely powerful, convenient input method for your watch app users.

Logging during development with Apple Watch hardware

Inserting breakpoints or logging statements (such as NSLog) is relatively straightforward with an iPhone-only iOS app. But how do you log from the WatchKit Extension (aka Watch app)?

The good news is that logging isn’t filled with many complicated steps. The bad news is that the logging works intermittently.

  1. Add your NSLog statements in your WatchKit Extension. This is probably your InterfaceController.m
  2. Run the watch app on iOS Device + watchOS Device (in the WatchKit App scheme)
  3. Select Debug > Attach to Process > (click on your watch app name)
  4. Profit! You should see your NSLogs when they are triggered in the app lifecycle in Xcode

debug

If logging isn’t working, try typical Xcode debug steps such as:

  • deleting the app on your phone & re-running it in Xcode
  • restarting the phone and/or watch devices
  • clean Xcode (cmd + shift + k) and re-run the app
  • quit & restart Xcode

Apple GameCenter Implementation Strategy

Having worked on my first app that implements GameCenter, I had a lot of questions about the process. The main question was how do I implement GameCenter into my app? Do I need to pick the right application template when creating my Xcode project? Do I need to use SpriteKit? Etc

The good news is that GameCenter can be added on after the rest of your application is ready. You should focus on your game mechanics, game engine, user friendliness, etc. After you are satisfied with the core experience, you can add GameCenter (leaderboard, achievements, and other features) afterwards. You can choose any application template and you don’t have to use SpriteKit.

In my app, I had both a phone app & a watch app. You will need to implement GameCenter using Apple’s GameKit Framework. GameKit is currently only for the iPhone, so GameCenter logic needs to be called in the Phone app.

I found great Apple documentation with the same advice:

Here’s a reasonable process to follow when designing a game that supports Game Center:

  1. Decide which Game Center features you plan to support.
  2. Define your game mechanics, keeping in mind the requirements and limitations of Game Center.
  3. Implement your game engine, ignoring Game Center for now. Focus on developing the other aspects of your game, such as your game engine and gameplay. You do this to avoid needing to create an iTunes Connect record earlier than you need to.
  4. [implement Game Center]

As with any app, focus on nailing the key user experience. Then worry about implementing/integrating GameCenter in your app.

Setup Apple Watch for Development Guide

While working in Xcode and running my watch app on my actual hardware watch for the first time, I ran into this error on my watch the first time: “Failed to install [app], error: Application Verification Failed.” This stack overflow answer provides the solution, but I wanted help illustrate the steps I took to fix the error. Disclaimer: this worked for me, but there are probably more optimal ways of fixing the error.

  1. In Xcode, get the UDID of your Apple Watch (WIndow > Devices). The UDID is labeled “Identifier” and you can double click on the Identifier device hash to select & copy it.
    1
  2. Visit the Apple Developer Portal at https://developer.apple.com/devcenter/ios/index.action and click on “Certificates, Identifiers & Profiles” in the right sidebar.
    2
  3. Click on Devices > All in the left sidebar.
    3
  4. Click on the Plus Sign (+) in the top right.
    4
  5. In Register Device, provide a Name (whatever you want) and your watch UDID (from step 1 above).
    5
  6. Submit the form to register your watch device.
  7. In “Certificates, Identifiers & Profiles”, locate your .watchkitextension Provisioning Profile for your app. Select & download this profile.
    7
  8. Locate your downloaded profile file on your computer & double click the Provisioning Profile.
  9. Restart Xcode.
  10. Build your project and you will encounter a iOS Development Certificate alert.
    10
  11. Warning, this step may be dangerous (proceed at your own risk). This worked for me. Click on “Revoke and Request”. This will revoke your current certificate and request a new one. You will probably get an email notifying you that “Your Certificate Has Been Revoked”.
  12. Run your Xcode project. Your watch app should now load the development build on your actual watch hardware.

About the author: Rex Feng enjoys iOS development and has released Pomodoro Pro for the iPhone & Apple Watch. You can follow him @rexfeng.

Pomodoro Pro WatchKit Architecture

My iOS app, Pomodoro Pro, is a constant work in progress. This post discusses how Apple Watch support was added to v1.1.0. Pomodoro Pro is a free, easy to use app for getting work done in continuous work & break cycles.

If you’ve looked into Apple Watch development, you’ve learned that the watch portion is an extension of your phone app. Your phone app is the brains of the operation, and your watch app relies on the phone app to do anything.

2 Way Event Binding Demo

From watch to phone

watch-final

From phone to watch

phone_8

App Lifecycle

With mobile development, it’s necessary to understand when a user will come into contact with your application. If the user comes across your application and starts using it when the visuals are incorrect, the user will lose confidence and not trust your application.

Working with Xcode and the watch simulator, my app has the following key lifecycle events:

  • watch starts up
  • watch resumes
  • watch actions (button presses) are reflected on both the watch & phone
  • phone actions (button presses) are reflected on both the phone & watch

Each of these events are essential for maintaining a consistent user experience that does not surprise the user.

Implementation

My implementation used MMWormhole for 2 way event binding. This means that the phone should know when a button was pressed on the watch and vice versa. Curtis Herbert has a great blog post on sharing data and events.

In order to have the phone app be responsible for the correct timer state, my phone app is responsible for returning a NSDictionary of the current timer properties. My watch app is able to get the NSDictionary and update the watch screen accordingly. It is important to note that my phone app is the ONLY source of the canonical current timer state. Trying to sync state between the phone and watch app would be a nightmare and a lot of work.

When the watch app starts, the watch app asks the phone for the current timer state (a NSDictionary) in order to set itself up correctly. When the watch app resumes from inactivity, it also asks the phone for the current timer state (a NSDictionary).

Using MMWormhole, I’m able to listen on events from the watch or the phone. When the user presses a button on the watch, the watch app passes a message to notify the phone, and the phone updates the timer state. Similarly, when the user presses a button on the phone, the phone app updates the timer state and notifies the watch app with the latest state.

Lessons Learned

  1. The phone app (not the watch app) is responsible for the correct state
  2. Use a Framework or shared classes (in File Inspector, add Target Membership) to DRY (don’t repeat yourself) out your codebase

Summary

With Pomodoro Pro, it was essential for a user to be able to start / pause / resume / stop the timer from either the phone app or the watch app. This required a way to manage the timer state (phone app) and have user actions occur on all screens (phone & watch).

In order to build a user friendly watch app, you should anticipate & identify where your app’s state and events come from. Make sure to account for those scenarios.

Pomodoro Pro v1.1.0 went live on 4/14/2015. Please let me know what you think @rexfeng

Fix no matching provisioning profiles validation issue

Here’s a quick problem & solution that worked for me. Hopefully this helps others out there.

Situation:

Validating an archive prior to submitting the build to the App Store, but it fails validation. I am using App Groups (for the phone app & watch app).

Problem:

Validating my archive created two “no matching provisioning profiles found” errors. The error was specifically related to “none of the valid provisioning profiles allowed the specified entitlements betareports-active com.apple.security.application-groups”.

Solution:

In my case, my development was able to use App Groups, but the production/distribution environment was not setup yet.

Under Provisioning Profiles > Distribution (https://developer.apple.com/account/ios/profile/), create an Distribution / App Store for each App ID that you need. In my case, I had to create one for the phone app & one for the watchkit extension. Make sure to download each after generating them. Double click on your downloaded files to automatically load them into Xcode.

When I tried to validate my archive again, I was able to successfully validate (after generating & loading my new Provisioning Profiles).

Standing on the Shoulders of Documentation

sprout123

Learning how to build a simple iOS app has not been bad. There’s a lot of learning how to find things in Xcode (protip: get a 2nd screen) and familiarizing myself with UIKit conventions. I completed the bitfountain iOS 7 course and have subscribed to more iOS newsletters than I care to admit.

At a meetup last year, I had a discussion about my choice to start with Objective-C. He asked me why I didn’t jump into Swift or use a tool like PhoneGap. Fast forward several months to today, I’m very happy I went with Objective-C. Whenever I am unsure how to do something in Objective-C, there are endless helpful blog posts and StackOverflow discussions out there. Even blog posts written before 2010 can be helpful. I am truly standing on the shoulders of all those heroic individuals who’ve tread down the path before me years ago.

With Swift, I’m sure there’s great documentation out there, but my guess is that Swift today (the beginning of 2015) cannot compete with the thoroughness of Objective-C edge cases discussed on the Internet.

Access to simple, basic questions like converting a NSUInteger to a NSNumber are essential for those just starting out. I’d like to use the example of an extremely beginner friendly resource, RailsCasts, which taught you how to use run of the mill gems, like Devise, and helped create a new generation of developers. Without a wealth of beginner accessible resources, a language or framework can’t grow or grow as fast.

iOS Programming

I’ve started learning iOS programming. Objective-C seems very low level, but it’s alright as an older object oriented language. Learning the Apple frameworks seems to the be tricky part. There’s a lot for me to learn with using Xcode (since I don’t normally use IDEs) and frameworks like Cocoa Touch.

I spoke to someone recently who suggested skipping Objective-C and going directly to Swift. Or even a tool like PhoneGap. Personally, I side with Aaron Hillegass’ take:

I have three messages for these people:

  • If you want to be an iOS developer, you will still need to know Objective-C.
  • Objective-C is easier to learn than Swift. Once you know Objective-C,
  • it will be easy to learn Swift.

To take a longer perspective on iOS, I want to build my foundation up from Objective-C to iOS. This is similar to how learning Ruby is critical for being a Rails developer.

With that said, I’m eager to get my hands dirty with iOS prototypes through different online courses.

How to unit test your JS and use it in the browser

Intro

Recently, I wanted to add test coverage to Halloween Bash and keep using it in the browser. This doesn’t seem to be an unreasonable request, but it turns out that it involves many things. You have many choices of test runners & testing frameworks, and I didn’t want to setup a SpecRunner.html to unit test my JS.

The setup that I ended up using is:

What you’ll need:

  • Your HTML/JS project (You can use my demo project)
  • NodeJS (I recommend the Installer from the Node homepage – click “Install”)

Try out the demo app that squares your input.

With my demo, my file structure looks like:

index.html
assets/js
assets/css

There are countless ways to organize your non-html assets, and my demo asset structure is intended to be easy to follow.

My demo contains jquery and two unit testable lib functions (multiply & square):

// define multiply()
window.unitTestJsDemo.multiply = function(x, y) {
  return x*y;
};

// define square()
window.unitTestJsDemo.square = function(x) {
  return unitTestJsDemo.multiply(x, x);
};

Setup NodeJS & GulpJS

Once NodeJS is installed on your machine, setup your node environment:

npm init

The npm init command will walk you through your project, ask you a series of questions, and setup your configuration in package.json.

Next, setup Gulp via npm on your command line:

// Install gulp globally
npm install -g gulp

// Install gulp in your project devDependencies
npm install --save-dev gulp

// Create a gulpfile.js at the root of your project
touch gulpfile.js

// gulpfile.js file contents
    var gulp = require('gulp');

    gulp.task('default', function() {
      // place code for your default task here
    }); 

// Run gulp default task
gulp

You now have Node & Gulp setup to run your Gulp tasks. The default Gulp task doesn’t do anything, but you can try it out by running gulp.

Setup gulp-jasmine

Save gulp-jasmine into your gulpfile.js:

npm install --save-dev gulp-jasmine

Create your tests:

mkdir -p assets/js/spec/lib
touch assets/js/spec/lib/multiply-spec.js
touch assets/js/spec/lib/square-spec.js

assets/js/spec/lib/multiply-spec.js will contain:

/* jslint node: true */
/* global describe, it, expect */

"use strict";

var multiply_lib = require('../../lib/multiply');

describe("#multiply", function () {
  it("returns the correct multiplied value", function () {
    var product = multiply_lib.multiply(2, 3);
    expect(product).toBe(6);
  });
});

assets/js/spec/lib/square-spec.js will contain:

/* jslint node: true */
/* global describe, it, expect */

"use strict";

var square_lib = require('../../lib/square');

describe("#square", function () {
  it("returns the correct squared value", function () {
    var squared = square_lib.square(3);
    expect(squared).toBe(9);
  });
});

Next, we’re going to move the unit testable functions (multiply & square) into node.js-style modules.

mkdir assets/js/lib
touch assets/js/lib/square.js
touch assets/js/lib/multiply.js

assets/js/lib/multiply.js will contain:

exports.multiply = function(x, y) {

  "use strict";

  return x*y;
};

assets/js/lib/square.js will contain:

var multiply_lib = require('./multiply');

exports.square = function(x) {

  "use strict";

  return multiply_lib.multiply(x, x);
};

Update your gulpfile.js to run the tests:

"use strict";

// Include gulp
var gulp = require('gulp');

// Include plugins
var jasmine = require('gulp-jasmine');

// Test JS
gulp.task('specs', function () {
    return gulp.src('assets/js/spec/lib/*.js')
        .pipe(jasmine());
});

// Default Task
gulp.task('default', function() {
  // place code for your default task here
});

gulp.task('default', ['specs']);

You’ve created your libs (multiply & square), the lib specs (multiply-spec.js & square-spec.js), and setup Gulp to run your tests with Jasmine.

square.js is setup to use the multiply.js lib through the Node require module syntax. Woot!

You can run the default task, which is setup to run your specs task. It should look like:

$ gulp
[16:29:18] Using gulpfile your/path/unit-test-js-demo/gulpfile.js
[16:29:18] Starting 'specs'...
[16:29:18] Finished 'specs' after 44 ms
[16:29:18] Starting 'default'...
[16:29:18] Finished 'default' after 20 μs
..

Finished in 0.008 seconds
2 tests, 2 assertions, 0 failures

Great! Your modules are unit tested (feel free to add more tests), and you want to use them in the browser.

Browserify your JS

Up to this point, we’ve been using jQuery through our local file at /assets/js/jquery-1.10.2.min.js. We’ll want to get rid of managing jQuery ourselves and let Node manage our jQuery dependency.

Let’s create a new file for our page’s JS to organize itself around:

touch assets/js/app.js

Add jQuery to your dependencies and remove your local copy of jQuery:

npm install --save-dev jquery
rm assets/js/jquery-1.10.2.min.js

assets/js/app.js will contain:

var $           = require('jquery');
var square_lib  = require('./lib/square');

$(function() {

  "use strict";

  $("#squareValue").change(function() {
    var $this       = $(this),
        squareValue = $this.val(),
        squareResult;

    // if squareValue is not numeric
    if (isNaN(squareValue)) {

      $("#squareResult").html('N/A');
      return false;

    // else squareValue is numeric
    } else {

      squareResult = square_lib.square(squareValue);
      $("#squareResult").html(squareResult);
      return true;
    }
  });

});

Now we need to use Browserify to build our JS file with gulp.

Add Browserify related dependencies into your gulpfile and setup your new task:

npm install --save-dev gulp-uglify
npm install --save-dev vinyl-source-stream
npm install --save-dev gulp-streamify
npm install --save-dev browserify

Update your gulpfile.js to include the new browserify task:

"use strict";

// Include gulp
var gulp = require('gulp');

// Include plugins
var jasmine     = require('gulp-jasmine');
var uglify      = require('gulp-uglify');
var source      = require('vinyl-source-stream'); // makes browserify bundle compatible with gulp
var streamify   = require('gulp-streamify');
var browserify  = require('browserify');

// Test JS
gulp.task('specs', function () {
    return gulp.src('assets/js/spec/lib/*.js')
        .pipe(jasmine());
});

// Concatenate, Browserify & Minify JS
gulp.task('scripts', function() {
    return browserify('./assets/js/app.js').bundle()
        .pipe(source('all.min.js'))
        .pipe(streamify(uglify()))
        .pipe(gulp.dest('./public/'));
});

// Default Task
gulp.task('default', function() {
  // place code for your default task here
});

gulp.task('default', ['specs', 'scripts']);

You’ll notice that we did a few things: declare new modules at the top through require, add a new gulp task called scripts, and update the default task to run our JS specs & scripts tasks.

At public/all.min.js, your new JS is ready to use in your browser.

Let’s remove the old file and update our index.html to use our new minified JS:

rm assets/js/main.js 

Remove the following lines from index.html:

< script src="assets/js/jquery-1.10.2.min.js">
< script src="assets/js/main.js">

Add the following line into index.html:

< script src="public/all.min.js">

Voila! Open up index.html in your browser and your square() function is working again.

Conclusion

GulpJS is an amazing tool to run tasks, and the Gulp streaming build system is very easy to read and understand.

There are countless tasks that you can setup on Gulp to lint your JS, compile your sass, etc. Livereload is useful for front end development.

Hopefully, the Unit Test JS demo helped you understand a simple example of using Gulp to run Jasmine unit tests and use the tested JS in your website.