Developer Blog

Modifying the iOS Settings.bundle Using Build Phases

Most iOS apps today communicate with a server to send and receive data. During development you may have several servers (QA, Staging, Prod) and oftentimes find that you need to distribute copies of your app pointing to each server.

A common approach here is to create a temporary “debug” page where you can configure which server you want your app to use.

This is a good solution but a more elegant one exists. The idea is to create a settings page in the iOS settings app, where you can select between servers or enter your own custom URL. This solution keeps debug code down to a minimum and is less disruptive not requiring an entire debug page created in the app.

Settings.bundle

In order to add an app setting page to the iOS settings app, you must create a Settings.bundle file.

Below is a simple example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
<dict>
  <key>PreferenceSpecifiers</key>
  <array>
      <dict>
          <key>Title</key>
          <string>Restart app after making changes</string>
          <key>Type</key>
          <string>PSGroupSpecifier</string>
      </dict>
      <dict>
          <key>DefaultValue</key>
          <false/>
          <key>Key</key>
          <string>use_dev</string>
          <key>Title</key>
          <string>ON-Dev OFF-Staging</string>
          <key>Type</key>
          <string>PSToggleSwitchSpecifier</string>
      </dict>
      <dict>
          <key>AutocapitalizationType</key>
          <string>None</string>
          <key>AutocorrectionType</key>
          <string>No</string>
          <key>DefaultValue</key>
          <string></string>
          <key>IsSecure</key>
          <false/>
          <key>Key</key>
          <string>custom_URL</string>
          <key>KeyboardType</key>
          <string>Alphabet</string>
          <key>Title</key>
          <string>Other (i.e. ab.com)</string>
          <key>Type</key>
          <string>PSTextFieldSpecifier</string>
      </dict>
  </array>
  <key>StringsTable</key>
  <string>Root</string>
</dict>
</plist>

And the resulting settings page:

Alt text

Build Phase Run Script

The problem with the above solution is that you must remember to remove the Settings.bundle file when archiving your app for the store.

Taking our solution to the next level, during an App Store build, the build phases run script can be used to zap this settings page and replace it with something useful. For the purpose of this blog, we will replace the page with the version number of the app.

Below is an example build phase run script that deletes the current settings when building for the App Store and creates new elements for displaying the app version number:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
if [ "$CONFIGURATION" == "AppStore" ] ; then

APPVERSION="`/usr/libexec/PlistBuddy -c \"Print :CFBundleVersion\" \"$CODESIGNING_FOLDER_PATH/Info.plist\"`"
SETTINGSBUNDLEPATH="$CODESIGNING_FOLDER_PATH/Settings.bundle/Root.plist"

/usr/libexec/PlistBuddy -c "Delete :PreferenceSpecifiers" "$SETTINGSBUNDLEPATH"

/usr/libexec/PlistBuddy -c "Add :StringsTable string 'Root'" "$SETTINGSBUNDLEPATH"
/usr/libexec/PlistBuddy -c "Add :PreferenceSpecifiers array" "$SETTINGSBUNDLEPATH"
/usr/libexec/PlistBuddy -c "Add :PreferenceSpecifiers:0 dict" "$SETTINGSBUNDLEPATH"

/usr/libexec/PlistBuddy -c "Add :PreferenceSpecifiers:0:Type string 'PSGroupSpecifier'" "$SETTINGSBUNDLEPATH"
/usr/libexec/PlistBuddy -c "Add :PreferenceSpecifiers:0:Title string 'Version Information'" "$SETTINGSBUNDLEPATH"

/usr/libexec/PlistBuddy -c "Add :PreferenceSpecifiers:1:Type string 'PSTitleValueSpecifier'" "$SETTINGSBUNDLEPATH"
/usr/libexec/PlistBuddy -c "Add :PreferenceSpecifiers:1:Title string 'Release:'" "$SETTINGSBUNDLEPATH"
/usr/libexec/PlistBuddy -c "Add :PreferenceSpecifiers:1:Key string 'appVersion'" "$SETTINGSBUNDLEPATH"
/usr/libexec/PlistBuddy -c "Add :PreferenceSpecifiers:1:DefaultValue string '$APPVERSION'" "$SETTINGSBUNDLEPATH"

fi

And the resulting settings page:

Alt text

Note that as an added benefit, using the Settings.bundle (even if it is just displaying your app version) is a good way to widen the footprint and exposure of your app since it will be listed in the main settings page.

Apple Sprite Kit Demo

With Xcode 5 Apple is releasing Sprite Kit, a great new tool for making 2D games that abstracts away a lot of boilerplate.

I threw together a quick demo using the Apple Adventure game as a reference. The code referenced in this blog post can be found here: https://github.com/asail77/OLTTSpriteDemo

As you scan through the code, you will notice that most of it is located in OLMyScene.h. With 541 lines of code, you are able to get a big bang for your buck! This is because Sprite Kit does most of the work for you. All you have to concentrate on is the logic of your game and the graphics.

Atlas Folders

One of the interesting features of Sprite Kit is the .atlas folder. Place a group of photos (i.e. a series of graphics for an action like “Goblin_Walk”) in the folder and Xcode will automatically create an atlas file when the application is packaged. You can see this by going to the package contents and opening one of the atlas folders. You will notice that all of the images are combined into a single image with some corresponding xml used to reference the original images.

The images are packed together and arranged in a way that results in less disk usage. Additionally, with less files to load from disk, you have better performance.

Note that -(void)loadWorldData is used initially to load all atlas and particle files before the demo begins. When these files are needed later, they are copied from memory rather than reloaded from disk:

1
SKEmitterNode *archerProjectile = [_archerProjectile copy];

This helps to ensure you are maintaing a good frame rate.

Partical Files

Another cool feature of Sprite Kit is the ability to create particle files and completely customize them. In Xcode, open up the Particle Files folder under Resources and view the .sks files to see this in action.

Note that for the ArcherProjectile particle file, I found that the particle would not travel nicely through the world (i.e. create a long trail) when “fired” by the Hero. This was solved by setting the target node to the world:

1
2
3
-(void)fireAtAntagonist {
  ...
  archerProjectile.targetNode = _world;

Action Chaining

One of my favorite features of Sprite Kit is the ability to chain actions together and attach them to an SKSpriteNode.

For example, when launching the spaceship, I want a few events to happen:

  1. I want the spaceship to follow a path that I calculate based on the position of all Antagonists in view, but I want this path to start on the left side of the screen and end on the right with a total time of 4 seconds.

  2. At the same time, when the spaceship is half way through its path (2 seconds in), I want all antagonists to be “killed” making it appear as if the spaceship has blown them up.

  3. After 4 seconds, when the spaceship has exited the screen, I want it to be removed from the world and released.

All of this can be achieved with the following:

1
2
3
4
5
6
  // Launch spaceship
  [_spaceship runAction:[SKAction group:@[[SKAction followPath:path asOffset:false orientToPath:YES duration:4],
                                          [SKAction sequence:@[[SKAction waitForDuration: 2],
                                                               [SKAction runBlock:^{[self killAllAntagonists];}],
                                                               [SKAction waitForDuration: 2],
                                                               [SKAction removeFromParent]]]]]];

Physics

Most of the code is self explanatory, with the update loop being used continuously to update the Hero and Antagonists. The physics callback of the render loop is not used here, but it is worth noting that I am using physics to prevent the characters from overlapping and to detect collisions:

1
2
3
4
5
6
7
8
9
- (void)createMoreAntagonists {
  ...
  // Set collision physics
  antagonist.physicsBody = [SKPhysicsBody bodyWithCircleOfRadius:50];
  antagonist.physicsBody.categoryBitMask = ColliderTypeAntagonist;
  antagonist.physicsBody.collisionBitMask = ColliderTypeProjectile | ColliderTypeAntagonist | ColliderTypeHero;
  antagonist.physicsBody.contactTestBitMask = ColliderTypeProjectile;
  ...
}

Defining the physical boundary of an object, setting the types of objects it can collide with, and deciding when to trigger collision events are all one liners. You can respond to collision events by implementing the didBeginContact method:

1
2
3
4
5
6
7
8
9
10
- (void)didBeginContact:(SKPhysicsContact *)contact {
  SKNode *bodyA = contact.bodyA.node;
  SKNode *bodyB = contact.bodyB.node;

  // Check for Hero projectile to Antagonist collision.  If found, blow up Antagonist
  if ([bodyA isKindOfClass:[SKEmitterNode class]] && [bodyB isKindOfClass:[OLAntagonist class]])
    [self blowUpAntagonist:(OLAntagonist *)bodyB];
  else if ([bodyB isKindOfClass:[SKEmitterNode class]] && [bodyA isKindOfClass:[OLAntagonist class]])
    [self blowUpAntagonist:(OLAntagonist *)bodyA];
}

End Result

Below is a screenshot of what to expect!

Alt text

Improving Abstraction and Testability by Removing Activerecord Callbacks

ActiveRecord gives software developers a way to hook behavior into a model during persistence related activities. This can come in handy, however, everything that can be done in a callback can be done in a better, cleaner way.

An example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
class User < ActiveRecord::Base

  has_and_belongs_to_many :badges

  before_save  :downcase_sensitive_fields
  after_create :send_welcome_email, :award_sign_up_badge
  after_save   :award_earned_badges

  private
  def downcase_sensitive_fields
    self.email = email.to_s.downcase
  end

  def send_welcome_email
    UserMailer.welcome_email(self).deliver
  end

  def award_sign_up_badge
    badge = Badge.find_by_name('Sign Up')
    self.badges << badge
  end

  def award_earned_badges
    badge = Badge.find_by_name('One Year')
    if created_at < 1.year.ago && !badges.include?(badge)
      self.badges << badge
    end
  end

end

We can improve this by moving each of the various callbacks to a more appropriate place and in the process simplifying our User model. This will allow the User model to focus on what it does best.

First, let’s look at the different types of actions that are happening. Our first callback is forcing our email to lower case, which is a data manipulation action to normalize the input into something we desire. Hooks that manipulate data can be replaced with overridden setters:

1
2
3
4
5
6
7
8
9
class User

  has_and_belongs_to_many :badges

  def email=(val)
    write_attribute(:email, val.to_s.downcase)
  end

end

Next, we see the other callbacks are things we want to happen either when a User is created or when it is saved. Lumping these actions into callbacks makes testing harder, as you often get unwanted side effects in your tests. As we see with the badges, it also means we have a strong reliance on Badge. You see this type of callback most often when someone has diligently followed the Skinny Controller/Fat Model paradigm. They know this code shouldn’t be in the controller, so they put it in the model and since it is related to saving the trend is to use callbacks.

We can improve this situation by creating a new class that will be in charge of knowing how to handle persistence related side effects. We’ll call it a UserService.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
class UserService

  attr_accessor :user, :mail_service, :badge_service

  def initialize(opts)
    @user = opts[:user] || User.new
    @mail_service = opts[:mail_service] || UserMailer
    @badge_service = opts[:badge_service] || BadgeService.new
  end

  def create(params)
    user.attributes = params
    user.valid? && create_user
  end

  def update(params)
    user.attributes = params
    user.valid? && update_user
  end

  private

  def create_user
    if (success = user.save)
      mail_service.welcome_email(user).deliver
      badge_service.award_badges(user, new: true)
    end
    success
  end

  def update_user
    if (success = user.save)
      badge_service.award_badges(user)
    end
    success
  end

end

class BadgeService

  def award_badges(user, opts)
    sign_up_badge(user, opts)
    one_year_badge(user, opts)
  end

  private
  def sign_up_badge(user, opts)
    if opts[:new]
      badge = Badge.fetch(:sign_up)
      user.badges << badge unless user.badges.include?(badge)
    end
  end

  def one_year_badge(user, opts)
    if user.created_at < 1.year.ago
      badge = Badge.fetch(:one_year)
      user.badges << badge unless user.badges.include?(badge)
    end
  end

end

This also gives us an opportunity to easily change how badges are awarded. We can see that there might be further areas we could improve. For example, we can shift the rules for badges to a BadgeRule class or into the Badge itself instead of the BadgeService knowing the logic for each badge. Since we are still directly using an ActionMailer for the welcome email it makes stubbing the mail_service clumsier, so we may want to further abstract that as well.

Now, our set of classes are much easier to test and it is clear what each class is responsible for. All of the business logic of what needs to happen when a user is created and saved can now be tested without a real user, real mailer, or real badges. This means no database hits and much faster tests.

Deploying Rails 4 to Heroku

Heroku is an excellent option for deploying your Rails 4 application and the following setup will allow you to get maximum performance for a minimal cost.

Application Design Choices

Choosing the right services and architecture can go a long way to maximizing performance on Heroku.

Application Server

You have a number of choices for application servers, however you will see your biggest performance gains using clustered Puma. This acts like Unicorn by utilizing several different processes (workers) but still has the mutli-threading provided by Puma. Since your rails app is going to be I/O blocked the vast majority of the time, you will benefit from this setup even on MRI. Add the puma gem to your Gemfile and add the following line to your Procfile:

web: bin/puma -C config/puma.rb -p $PORT

Then in config/puma.rb put:

1
2
3
4
5
6
7
8
9
workers 4
threads 16,16
preload_app!

on_worker_boot do
  ActiveSupport.on_load(:active_record) do
    ActiveRecord::Base.establish_connection
  end
end

Background Jobs

You should be sending any non-trivial processing to a background job. The best way to maximize the use of your worker dynos is to use sidekiq for your job queue solution. Add the gem to your Gemfile and add the following line to your Procfile:

worker: bin/sidekiq

Optionally you can adjust the number of threads it uses. If most of your jobs are I/O bound try increasing the number of worker threads from the default 25. You can do this with the -c 50 option.

Database

Heroku can support a number of different database options through the Heroku Addons, however the default is Postgres. Postgres has a number of features that give it a great deal of flexibility including support for Hash and Array fields. I highly recommend you use Postgres locally for development as well instead of sqlite. Just add the pg gem to your Gemfile.

Unless you tell Heroku otherwise, you will have a development database which has a number of restrictions. The database has no caching, a limited connection pool, and a limitation on the number of rows you can have in your tables.

Any production application should be using Crane or better which can be added using the web interface or the command line. This will give you a base level of caching, no limitation on the number of rows, and a large 500 connections limit. Depending on your database size and usage you may wish to choose a larger database option which increases your cache.

Amazon S3

If you do any processing of images in your application, I recommend using Carrierwave and storing the images on S3. Furthermore, to reduce any chance of time-outs on uploads, I suggest having your forms upload direct to Amazon S3 and placing a job in Sidekiq to pull the image, process it, and place the processed images back on S3.

Also, rather than having your application serve assets (doesn’t it have something better to do??), look at adding the asset_sync gem to your project. This will allow you to hook into the asset precompile step and ship all of your assets to Amazon S3. Then just set your asset_host to your S3 bucket.

Heroku Rails 4 Support

Heroku treats logs as streams. If you add the following to your Gemfile, your app will handle logging as you expect and will be set to serve assets as well.

gem 'rails_12factor', group: :production

Heroku Ruby 2.0 Support

You should tell Heroku what version of Ruby to use. You can do this in your Gemfile by placing the following line:

ruby '2.0.0'

Heroku Addon Recommendations

Heroku has a large number of very useful Addons, many of which have free options.

PG Backups

Heroku will back up your database but you have to ask them to! Make sure you add on PG Backups. It’s free and you are silly not to. I recommend the “Auto – One Month Retention” option.

Redis (Pick One)

If you added Sidekiq to your application as I have suggested, you need a Redis Addon. There are a number to choose from and some have free tiers which provide plenty of space for your Sidekiq job queue. If you use Redis in other places in your application or expect a large queue depth, then select a larger package as necessary. I’ll leave it up to you to compare price and service.

Memcachier

You can use Redis as your cache store for Rails, but if you use memcache, you can get more cache for your cash using Memcachier, including 25MB in their free tier.

Logs

Heroku logs are not great. That’s probably an understatement. I highly recommend adding in a logging Addon such as Papertrail or Loggly.

Mandrill

Despite the horrible name, if you want to send email from your app, you should look at Mandrill. It is the transactional email service offered by Mailchimp. It works great just as an smtp server but has excellent bonus features like success tracking, open tracking, and you can use your Mailchimp templates.

New Relic

You get the basic version for free, but again you have to tell Heroku you want it. Just add the addon, include the gem in your app and optionally modify the config file. You then get excellent stats of your application performance.

Extra bonus, you can use New Relic’s availability monitoring to keep a single dyno application alive. Just set up availability monitoring and give New Relic and url on your app to ping. I highly suggest creating a specific ping end point that does nothing so it is the lightest load on your application as possible.

Additional Monitoring

I suggest adding some additional monitoring and/or error reporting. Services like Airbrake and Honeybadger both have Heroku Addons that make managing your application errors easy.

Others

There are of course a large number of other Addons which may enhance your application or make your life easier. I suggest browsing through them all and looking for things that will specifically help your particular application.

Wrap Up

So let’s talk about price as that always seems to come up when Heroku is brought up as an option. Let’s first layout what the minimum actually looks like for a true production grade application:

  • Web Dynos (1): Free (See New Relic Tip)
  • Worker Dynos (1): $35
  • Database (Crane): $50
  • PG Backups: Free
  • Redis (Redis Cloud 25MB): Free
  • Memcachier (25MB): Free
  • Papertrail (10MB w/2-Day Search): Free
  • Mandrill (12K Emails/Month): Free
  • New Relic: Free
  • Airbrake (Dev): $9

Total: $94/month

But that’s just the minimum so let’s be realistic and look at what a production application that gets any real amount of traffic actually needs:

  • Web Dynos (2): $35 (1 is Free)
  • Worker Dynos (1): $35
  • Database (Kappa): $100
  • PG Backups: Free
  • Redis (Redis Cloud 25MB): Free
  • Memcachier (250MB): $25
  • Papertrail (100MB w/7-Day Search): $15
  • Mandrill (40K Emails/Month): $5.95
  • New Relic: Free
  • Airbrake (Production): $25

Total: $341.95/month

There are surely cheaper hosting options out there that will give you the same or better performance for less money, however you have to ask yourself as a small start up the following question:

Do I want to spend my time developing my application or maintaining it?

If I don’t spend all the time setting up servers and services, and performing regular maintenance, backups, and worse fixing things when they break, I need to hire someone to do this for me. The best case scenario is you may be able to find an admin to handle all of this on a part-time basis, but even at part time you are probably spending at least $500/month.

So, find out what cheaper hosting solution you would like to use, factor in any of the services provided by Addons that you are not going to set up yourself on this platform. Whatever that total is, take the delta from your Heroku bill. If this difference is less than you can hire someone to do the work for you, then you can start considering options other than Heroku. Until then, reduce your stress and just git push heroku.