Adjusting the iOS deployment target with Cordova Hooks & NodeJS

This is a recipe to help you automatically setup your iOS deployment target. In this case, amending the setting of a Cordova/PhoneGap generated project to iOS7+.

It’s part of my upcoming recipes book that helps you easily deploy your Cordova apps. Do sign up here for updates!

Automation is ideal as it prepares our project for a Continuous Integration flow. You can constantly recreate a platform with the confidence that it has been configured correctly. We’ll be scripting our Cordova hooks using the mighty NodeJS.

Hooking the hooks #

Hooks live in a hooks directory under the main project folder. We target the after_platform_add CLI event so the adjust_ios_deploy_target.js script is added to a similarly named folder.

| Project /
|+ hooks /
|++ after_platform_add /
|+++ 001_adjust_ios_deploy_target.js

The 001_ file prefix preserves the running order in a hooks directory. Also, hooks have to be executable.

$ chmod ugo+x 001_adjust_ios_deploy_target.js

Wiring up the Node.js modules #

We should have Node.js already installed as the Cordova CLI depends on it. Our script utilises 2 node modules that are configured in a package.json file in the root project folder.

{
  "name": "project",
  "version": "0.0.1",
  "devDependencies": {
    "shelljs": "*",
    "xcode": "0.6.2",
  },
  "engines": {
    "node": ">=0.8.0"
  }
}

We can now install them using npm,

$ npm install

Scripting #

Essentially, our hook will do the following:

It can be summarised as the following (minus some obligatory helper code):

var xcodeProject = xcode.project(projectPath);

xcodeProject.parse(function(err){
  if(err){
    shell.echo('Error: ' + JSON.stringify(err));
  }
 else{
   var buildConfig = xcodeProject.pbxXCBuildConfigurationSection();

   propReplace(buildConfig, 'IPHONEOS_DEPLOYMENT_TARGET', '7.0');

   fs.writeFileSync(projectPath, xcodeProject.writeSync(), 'utf-8');
  }
});

As you can see, all the heavy lifting is provided by the xcode node module.

Here’s the complete hook: https://gist.github.com/the-experimenters/36a28cf2a43fd6e1c5d1.

Putting it all together #

Now, every time you add a platform using:

$ cordova platform add ios

An after_platform_add event is fired. This will trigger our hook and ensures the newly generated platform has a deployment target correctly set with iOS7 - hell yes!

In closing #

This skims the surface of what can be achieved with hooks. My upcoming deployment recipes book uses this awesome CLI feature to help you build apps predictably and confidently.

Get stuck in and make Cordova/PhoneGap work for you!

 
153
Kudos
 
153
Kudos

Now read this

Can you easily deploy your Cordova/PhoneGap apps?

99 problems # Houston, we have a problem! It’s failing, our app is constantly breaking UAT - but nothing has changed. Apart from we now build from JS and generate our iOS platform project on the fly. Could that be it? Why would that be... Continue →