Archive for 'Programming'

Background Fetch Caveats

Couple interesting posts lately about background fetch resource usage. If you’re not familiar with background fetch, that’s an iOS 7 thing that’s explained quite nicely in’s Multitasking in iOS 7 article:

Background Fetch is a kind of smart polling mechanism which works best for apps that have frequent content updates, like social networking, news, or weather apps. The system wakes up the app based on a user’s behavior, and aims to trigger background fetches in advance of the user launching the app. For example, if the user always uses an app at 1 p.m., the system learns and adapts, performing fetches ahead of usage periods. Background fetches are coalesced across apps by the device’s radio in order to reduce battery usage, and if you report that new data was not available during a fetch, iOS can adapt, using this information to avoid fetches at quiet times…

But the naîve user may find a surprise in wait:

An Unexpected Botnet

… There is, however, an intrinsic danger in applying this ability without fully thinking through the implications. When enabled within your applications you are essentially building a massively distributed botnet. Each copy of your application will be periodically awoken and sent on a mission to seek and assimilate internet content with only the OS safeguards holding it back. As your app grows in popularity this can lead to some rather significant increases in activity…

Here are the feed request frequencies for various Background Fetch enabled podcast clients … For an RSS feed that changes only once per week just these apps produce 126k web requests each week (out of 160k across all aggregators ). The feed itself is 450KB (49KB gzipped). Where it not for HTTP caching/compression (discussed later) this would be generating 56GB of almost entirely unnecessary downloads each week…

That is, indeed, a lot of almost entirely unnecessary downloads. The developers of Castro chimed in here:

The Value of Background Fetch [Point]

… Our strategy with Castro has been to employ Background Fetch to help us avoid the ongoing cost of a server. Castro polls each subscribed feed from the app regularly and posts local notifications when new episodes are found. There are pros and cons to this approach.


  • We spend no time on web app development or money on server hosting. Xcode is always open.
  • We have no scaling concerns.
  • The continued functionality of the app is not dependent on future sales.
  • There are fewer points of failure.


  • Worse update performance since the app hits every individual feed, rather than one centralised server.
  • A central server gives developers flexibility to fix individual feed issues, like poorly formatted dates or duplicate episodes for example…

Well, being big believers ourselves in not doing work we don’t have to, that makes a pretty compelling argument, indeed. But hark! Here’s a counterpoint from coming soon Castro competitor Overcast author Marco Arment:

The Value of Background Fetch [Counterpoint]

… Service-backed apps still have a lot of advantages and exclusive capabilities over iOS 7’s Background Fetch. I think server-side crawling is still the best choice for podcast apps and feed readers, for which users want fast updates to collections of infrequently updated feeds.

Overcast has been crawling tens of thousands of podcast feeds every few minutes for the last 6 months using standard HTTP caching headers. In the last week, 62% of all requests have returned 304 (“Not Modified”). Many of the rest returned the entire “new” feed, but none of the episodes had actually changed, making the server download and process hundreds of kilobytes unnecessarily.

An app using Background Fetch needs to make all of those fruitless requests just to get the handful of occasional changes. All of those requests cost processor time, memory, battery power, and data transfer. And each copy of the app needs to download those hundreds of wasted kilobytes when a server erroneously reports an unchanged feed as new…

A server can simply send a silent push notification to all subscribed apps when there’s new data in a feed, and each app can download just the changes. With infrequently updated feeds, like podcasts, this leads to huge savings in battery life and transferred data over time…

Well, there’s that too. So yeah, if you can’t count on decent 304 support, background fetch is not your resource-optimal choice no.

Lots of good numbers to crunch through, so read the whole posts. Personally, if the choice for your particular application is less than immediately obvious, we’d recommend implementing both methods; that way, if your service goes down, or you stop paying for it, or whatever, the app can remain functional. Safety first and second, that’s us!


Apropos of things to do to avoid users calling out your app as battery-hogging, take a gander at The Ultimate Guide to Solving iOS Battery Drain

Continue Reading →

All About Strings

Are you reading If not, you should be. Check out issue #9 for more than you ever realized you didn’t know about strings. Yes, strings.

Quick now: How do you correctly find the length of a string containing odd characters like emoji? And how can you be certain you’re comparing strings with combining characters for visible equivalence correctly? If the answers don’t spring to mind, check out NSString and Unicode.

How do you correctly, i.e. locale-aware, join a list of items for text display? That’s one of the many tidbits in Working with Strings.

No doubt you know how to use localized .strings … but did you know in iOS 7+ you can do locale-aware plurals with .stringdict files? And do you know how to correctly display a localized file name? See String Localization.

Need to validate your input? Or have a full expression grammar? Check out String Parsing.

Finally, know how to calculate bounding rects for attributed strings in the new non-deprecated iOS 7 way? And how to lay out hanging indents for lists and decimal-aligned number tables with Text Kit? If not, here’s String Rendering to get you up to speed.

Haven’t seen a developer periodical this consistently high quality through issue #9 since … well, ever, actually … so we strongly encourage you all to subscribe with their app to keep the goodies coming!


Extending “strings” to include “text” — Open Source Library And Editor Tool For Easily Formatting Text Within Your Apps

Continue Reading →

Custom Keyboards

For our Underutilized iOS Feature Of The Week award, how about UITextField/UITextView’s inputView field? Probably pretty much totally overlooked it, haven’t you? Here’s a sample implementation for next time something like that strikes your fancy (h/t: iOS Dev Weekly):

venmo / VENCalculatorInputView: Calculator keyboard used in the Venmo iOS app:


If you don’t have custom input needs but just want to improve the regular keyboard experience, there’s news for you too: Fleksy has released an iOS SDK that lets users long press to switch keyboards, if they’ve installed the free Fleksy app:

Screen Shot 2014-02-23 at 2.34.47 PM.png

And here’s another project to improve the default keyboard:

tonqa / JustType – The Better Keyboard for iOS

JustType is a keyboard extension using swipe gestures, highlighting and suggestions. It is built to be used in any iOS text editor and all text-intensive iOS apps. And it is really easy to use. If you want to have a video demonstration you can find it on this blogpost.

And just as a side caution, if you do get all excited to implement a custom keyboard with transparency and it displays funny in iOS 7, check out this Stack Overflow question!

Continue Reading →

Design Prototyping: Origami

This is a pretty nifty approach to prototyping your interface:

Screen Shot 2014-02-01 at 7.33.20 PM.png

Most designers today create static mockups to communicate app ideas. But increasingly apps are anything but static, which means as designers we need a better tool for interaction design.

Origami is a free toolkit for Quartz Composer—created by the Facebook Design team—that makes interactive design prototyping easy and doesn’t require programming…

Neat. And it made #1 on this list of 10 interactive design prototyping tools to check out, no less.

Check out the introduction post here, and if that looks interesting download it from the link above, follow @FacebookOrigami, and if you want to get out on the bleeding edge the repo is at facebook / origami!

h/t: iOS Dev Weekly!


Facebook Develops A Photoshop For Interaction Design, And It’s Free For Anyone To Use

Prototyping with Facebook Origami

ideo/avocado : A Toolbox For Creating Interactive iOS App Prototypes Enhancing Facebooks Origami

Continue Reading →

Animation: Canvas

Feel like adding a little gratuitous animation to your interface? Here’s a library that makes that easy:

Screen Shot 2014-01-28 at 7.11.10 AM.png

“Without code”? Huh? What they mean is that you can configure animations directly in storyboards:

Screen Shot 2014-01-28 at 7.04.02 AM.png

Helps out with custom fonts, blurred backgrounds, and other goodies as well. Check out the usage guide here, CanvasPod / Canvas on github, and follow @CanvasPod if that looks handy!

h/t: iOS Dev Weekly, ManiacDev!

Continue Reading →

Optimizing Network Traffic: CocoaSPDY and FastCoding

Ever have discussions of this pattern?

BOSS: Do me this obviously ludicrous so data heavy as to be next to impossible to make work at all network-based thing.

YOU: Uh … ok. <do next to impossible thing>

BOSS: It’s too slow! And too expensive! Waaaaaah!

Here’s a couple of options to be aware of when you’re trying to squeeze every last bit of juice out of your network traffic:

CocoaSPDY: SPDY for iOS / OS X

For over a year now, Twitter has supported the SPDY protocol and today it accounts for a significant percentage of our web traffic. SPDY aims to improve upon a number of HTTP’s shortcomings and one client segment in particular that has a lot of potential to benefit is mobile devices. Cellular networks still suffer from high latency, so reducing client-server roundtrips can have a pronounced impact on a user’s experience…

One of our primary goals with our SPDY implementation was to make integration with an existing application as easy, transparent, and seamless as possible. With that in mind, we created two integration mechanisms—one for NSURLConnection and one for NSURLSession—each of which could begin handling an application’s HTTP calls with as little as a one-line change to the code…

We’re still actively experimenting with and tuning our SPDY implementation in order to improve the user’s experience in our app as much as possible. However, we have measured as much as a 30% decrease in latency in the wild for API requests carried over SPDY relative to those carried over HTTP.

In particular, we’ve observed SPDY helping more as a user’s network conditions get worse…

If you’re slow because you’ve got a whack of back and forth traffic with a SPDY-enabled data source, this could be a pretty big win — as noted above, especially with the absolutely horrible latencies seen on cell networks that us developers tend to overlook since we’re always developing with wifi connected.

More likely though, your only big wins are going to come from optimizing your data representation, optimizing its JSON, switching to binary plists, and so forth, and here’s an interesting-looking new option to consider for that step:

nicklockwood / FastCoding: A faster and more flexible binary file format replacement for Property Lists and JSON

FastCoder is a high-performance binary serialization format for Cocoa objects and object graphs. It is intended as a replacement for NSPropertyList, NSJSONSerializer, NSKeyedArchiver/Unarchiver and Core Data.

The design goals of the FastCoder library are to be fast, flexible and secure.

FastCoder is already faster (on average) for reading than any of the built-in serialization mechanisms in Cocoa, and is faster for writing than any mechanism except for JSON (which doesn’t support arbitrary object types). File size is smaller than NSKeyedArchiver, and comparable to the other methods.

FastCoder supports more data types than either JSON or Plist coding (including NSURL, NSValue, NSSet and NSOrderedSet), and allows all supported object types to be used as the keys in a dictionary, not just strings.

FastCoder can also serialize your custom classes automatically using property inspection. For cases where this doesn’t work automatically, you can easily implement your own serialization using the FastCoding Protocol…

Looks like a pretty nice set of advantages for your local serialization needs, and would likely be applicable to network transmissions as well; the format is simple chunk based so should be easy to create/parse as applicable with your network service development environment of choice.

As always, if you’ve got any more unconventional or obscure tricks you use to speed up and/or cut down size of your network traffic, let us know!

Continue Reading →

Cocos2D V3 + SpriteBuilder 1.0

Not too many open source projects survive the founder leaving, most especially when it’s to a direct successor of that project, but those of us who were distinctly out of sorts at the thought of sacrificing our friendly Objective-C Cocos2D in blood and tears to the fixation on the cross-platform development chimera of the people who pay us to have fun can celebrate today:

Cocos2D V3 RC1 release

We are excited to announce the coordinated release of Cocos2D V3 and SpriteBuilder 1.0!

This release of Cocos2D brings three major improvements to the Cocos2D community: SpriteBuilder, which is a professional GUI editor for easy iteration on games; Chipmunk2D integration for rapidly developing physics-based games; and Apportable support out-of-the-box for all this, so that your Objective-C games can run on Android!

So for those that haven’t been keeping score so far, the number of cross-platform development environments using Objective-C just went from zero to one. Pretty cool, huh?

SpriteBuilder’s visual editor enables developers to quickly prototype and build high quality games with intuitive, elegantly designed tools. Designers and developers can work seamlessly together and drastically cut development time. SpriteBuilder is the only game development suite that allows you to run your Objective-C code as a native app on Android. Apportable compiles Objective-C programs directly to ARM or x86 machine code, so a game built with SpriteBuilder will run faster on Android than a game written in Java or other languages…

And what’s awesome sauce on that awesomeburger is that SpriteBuilder is open source, so writing yourself a custom level editor just difficulted down fantastically to boot. Check out this reddit Q&A for some more interesting tidbits.

If you’re in a hurry to check it out, as you should be, here’s the Getting Started page, and there’s already some tutorials and demos out there:

How To Make A Simple iPhone Game with Cocos2D 3.0 Tutorial

Clone Angry Birds with SpriteBuilder

CocoRoids: Example game for Cocos2D v3 using CCPhysics and SpriteBuilder features.

CCPhysicsColorMatch: A simple CCPhysics based color matching game.

We’re certainly hoping this investment works out well for Apportable; can’t think of any other development suite anywhere where the tool chain is fully open sourced and also backed by a sustainable revenue model, which aligns the interests of everyone involved in remarkable consanguinity. So do your part by paying up to Apportable for at least an Indie license, so they can keep their “about seven engineers” working on it!


The Guide to Building and Customizing SpriteBuilder v1.x

Building a real time multiplayer game with SpriteBuilder

Layouting with SpriteBuilder and Cocos2d 3.0

Migrating to cocos2d-iphone v3 – Tips & Tricks

Using PhysicsEditor with Cocos2D V3

Continue Reading →

Tip: Secure Charles Cert

No doubt if you’ve done any web-using apps or applications you’re familiar with Charles Web Proxy for debugging — and if not, go check it out right now — but there is the niggling concern that when you use it to debug SSL communications you tell it to trust Charles’ root cert, which leaves a hole open for anyone who cares to sign themselves a cert and go to nefarious work on your device.

But fear not! If like us you’d managed to overlook this option so far, here’s a step by step guide to setting up a

Custom SSL Certificate With Charles Web Proxy

Luckily Charles supports using your own custom SSL certificate as the root certificate, which you have to create yourselves. This can be done using openssl. You will be asked some information about the certificate. I recommend at least setting Organization Name to something meaningful as for instance Charles Proxy Custom SSL certificate. This makes it easier to find the certificate in Keychain…

… Now simply select the charles.pfx file in Proxy Settings > SSL > Use a Custom CA Certificate in Charles. Notice that Charles only saves the path to the file, so place the file somewhere meaningful.

Remember to install the certificate in keychain by simply opening the charles.crt file. It can be installed in the iOS simulator by dragging the charles.crt into the simulator window and on your iOS device by sending it using email. Remember to delete the old Charles certificate if you had it installed.

Worth doing just in case, yep. And if you’re OCD enough to get annoyed entering the password each time, the article goes on with how to trick Charles into thinking your custom cert is its default and skip that. We’re good with QA having to know the password, personally, so we’ll leave over that part.

h/t: iOS Dev Weekly!

Continue Reading →

Objective-C Style Guides

Ah, the great thing about standards is there’s so many to choose from. And here’s a new style standard for all us Objective-C programmers, from everybody’s favourite tutorial centre:

…the team and I are very pleased to announce the official Objective-C style guide!

This style guide is different from other Objective-C style guides you may see, because the focus is centered on readability for print and the web. Many of the decisions were made with an eye toward conserving space for print, easy legibility, and tutorial writing…

Pretty conventional most of it; the most interesting is this bit, which after due consideration we’ve decided has successfully convinced us that private properties add enough flexibility to be worth the smidgen of extra complexity:

The part of the guide that was the most controversial by far was the answer to this question: Should you prefer private instance variables, or private properties?

Main argument for preferring private instance variables: Do the simplest possible thing that works (and prefer saving space). Why add the overhead/complexity of private properties if you don’t need them?

Main argument for preferring private properties: Properties bring a lot of Objective-C goodness such as key-value coding, future proofness, a little more consistent overall.

Both approaches are completely valid ways of doing things, and both sides had valid points. However, we felt we should choose one for consistency’s sake.

After a heated 118-comment discussion, StackOverflow discussion, and very close vote, private properties won the day – at least for now :]

[EDIT: Worried about overhead? Check out Should I Use a Property or an Instance Variable? Spoiler: Property.]

And if you get down to the end there’s a list of other style guides, including a few that are new to us:

Personally, rather than set out a style guide as such, we loosely follow these principles:

  1. Clarity. There’s always at least two programmers on a project — you, and you coming back to fix bugs sometime down the road once you’ve completely forgotten what on earth you were thinking when you wrote this junk. Make it easy for the second programmer to understand looking at a single screenful what’s going on at any given line assuming no known/remembered context whatsoever.
  2. Malleability. Separate conditions and consequences; separate not necessarily connected actions; restrict scope to practical minimum. Easier it is to manipulate the code, the fewer bugs you’ll have and the quicker they’ll get fixed. This is why Allman style is The One And Only Correct Bracket Methodology: see the conditional compilation example at the end of that link’s section for the definitive demonstration of why.
  3. Terseness. Given two semantically identical structures, pick the shorter form. Note that this puts us at odds with common practice in the case of dot-notation syntax, as expressed in the style guide (cribbed from the NYT’s, apparently): “Dot-notation should always be used for accessing and mutating properties, as it makes code more concise. Bracket notation is preferred in all other instances…” Uh, why? Property-related calls are functions, “all other instances” are functions too. What is the magical unstated difference here that somehow makes concise only a virtue for functions that (conceptually) wrap value storage, and not for all functions? Not seeing any, dude. Use UIApplication.sharedApplication.delegate, or UIColor.whiteColor? Well, why not?
  4. Verifiability. Always write code in a fashion that allows the strictest compile time checks possible. So you should never use “id” for anything with a modern compiler. Use “instancetype”, or a protocol consisting of all calls potentially made to that object. Likewise, use NS_ENUM for enumerations.
  5. Mothership Consistency. If you can’t form a clear argument based on the first four points, go with the style used by the majority of Apple’s SDK headers and/or recent sample code. Most commonly resorted to in the case of holy wars over whether there’s a space in (NSString *)argument or whether it should be a spaceless (NSString*)argument and similar near totally pointless quibbles.

For the most part the style guide is perfectly compatible with these principles, the quoted artificial restriction without any justification given on use of dot notation is the only thing that jumps out at us as pointlessly silly. And we’d quibble with the K&R brace style, but wanting to save a line is defensible targeting print instead of our 27+” monitors, so we’re ok with that given the purpose. As opposed to all these other ones in the list, which all advocate K&R it appears; they’re just indefensibly wrong there, which is much worse than defensibly wrong. And none of them save Github’s are even somewhat close to our “everywhere, why not?” stance on dot notation. Hmmm, maybe we will get around to writing a Trollwerks Style Guide, sometime this millennium we run short of fundamentally meaningless things to argue about. But it won’t be soon.


An Xcode Plugin Enabling Easy Use Of The Clang Source Code Formatting Tool

Objective-Clean will set code to follow dozens of rules … and can get Xcode to throw build errors if you violate them.

Continue Reading →

Review: Unity 3D Game Development by Example

So, as we mentioned last time, we’d decided that it’s just about time to get to know the Unity game engine development environment a bit, and Packt Publishing was gracious enough to provide a review copy of their Unity 3D Game Development by Example video course to help us out with that!


The fast, easy way to start developing Unity games

There’s no better way to begin building impressive video games than Unity. The free software gives you the tools you need to create stunning 3D games and publish them for computers, phones, tablets, and the web.

This friendly video course will teach you the Unity from scratch and develop fun example games, deploying them to your favourite platforms…

TL;DR: Most Excellent orientation walkthrough — just exactly the level of getting our feet wet enough to be comfortable if we absolutely had to dive in that we were looking for. Unqualifiedly recommended as your introduction to Unity if you’re Windows and Android centric, minor qualification if you’re OS X and iOS centric that it’s a just a bit of an ill-fitting suit, not perfect but not too hard to match up with either.

Walkthrough Notes: What you download is a folder of HTML-wrapped browser-presented video — reputed to work on any modern desktop browser, but not iOS devices — split up into eight sections:

Section 1. Learning How Unity Thinks [22:01 mins]: Understanding Unity UI; Unity 3D Project Structure; Game Objects and Components; MonoDevelop Explained; Creating your first Component; Pro-Tips: Understanding A MonoBehavior

This section jumps right in to describing the main window, so it assumes that you’ve already figured out how to get Unity installed on your system. Which is a simple and free download, we got version 4.3.2. The video is taken on a Windows machine and the screen is arranged moderately differently than how the sample project shows up in said 4.3.2 OS X download, but nothing that makes any real difference, we thought … until it said “use the middle mouse button to pan”. Yeah, that’s a tough one for us. OK, so it’s not perfect for the OS X user. Still, it’s pretty darn close. We’re also informed that if we don’t know C# we should go learn it first as that’s what all the scripting examples will be in. Yeah, that’ll happen. But any C-ish syntax knowledge is fine to follow along with this course.

Section 2. Building a Scene [16:13 mins]: Creating and Loading a Scene; Building and Manipulating GameObjects; Adding Components to GameObjects; Building and Using Prefabs; Pro-Tips: Understanding Unity Cameras

All pretty straightforward, and workable if not precisely elegant. Yep, we’re starting to see why Unity is widely considered the premier design environment.

Section 3. Scripting Interactivity [20:26 mins]: Component Basics; Useful pre-built components; Trapping Player Input; Communicating Between Game Objects; Pro-tips: Building a Messaging System

On the other hand, nothing to confirm your low opinion of the development environment like finding out that building a messaging system is considered a “pro tip” instead of something taken for granted, that’s for sure. And this MonoDevelop thing you use to write your C# scripts in … well, it’s no Xcode, that’s for sure. Prejudice about this kind of environment being suited well only to projects that don’t involve any serious programming: Confirmed.

Section 4. Sound and Music [17:49 mins]: Unity Audio Basics; Building and Playing Game Music; Adding 3D Audio to the world – Controlling Audio Sources; Pump Up the Volume – Setting Volume and controlling Music Playback; Pro-Tips: Saving Player Preferences

Another straightforward section to breeze right through. Saving preferences counts as a “pro tip” as it points out the existence of System.Xml.Serialization. Yep, if you’re used to iOS SDK programming adopting this is going to be quite the shock.

Section 5. Building UI [30:51 mins]: Unity GUI Basics; Skinning your GUI; Game Experience as GUI; Game Experience as GUIScore and Time Displays; Pro-Tips: Pausing and Ending a Game Round

By “UI” here they mean HUD-type displays.Throws in some side tips like internal glows to add a little style to the experience too.

Section 6. Finishing the Game – Title Screens and Menus [11:38 mins]: Building a Title Screen; Building the Main Menu; Pro-Tips: Create a Pause Menu by Reusing your Work

Which is tying together the screen creation and GUI layout stuff that we’ve been introduced to already.

Section 7. High Score (Saving and Loading) [19:28 mins]: Tracking Player Score in Your Game; Building the High Scores List; Displaying High Scores from the Main Menu: Pro-Tips: Building your Finished Game

Some more UI/navigation tweaks, and how to output a Windows executable. Which differs by only one popup selection from outputting an OS X executable.

Section 8. Where to Go from here [27:00 mins]: Extending Your Work – Expand Score into Combo Scoring; Where to Go From Here – The Unity Community; Where to Go From Here – Unity 3D Pro; Where to Go From Here – Porting to Android; Pro-Tips: Publishing Your Finished Game

And of course being a person of taste and style Dear Reader, you have no use for the bits on how to publish on Android, but no doubt the pitiable intern you fost that nonsense off on will find that bit of interest. No mention of iOS in the porting bits, but presumably touch handling would be similar and looks like controls are about the only necessary difference.

So overall, we’re quite completely satisfied with how that went for the time investment. Nice efficient introductory walkthrough touching on enough to get off to a flying start yourself without getting bogged down or distracted much of anywhere; and if you’re doing simple games, that’s all you need! Would have been nice to something that was OS X aware, but there’s only a couple of places where things like referring to the middle mouse button show up, no particularly big deal. On the other hand, we were just a touch disappointed to not find any discussion of porting and native code integration across various platforms, a little more discussion of that as opposed to “here, add a touch handler and you’ve ported to Android” would be rather welcome. But that’s mainly because being a real — that is, iOS — developer, our skin was crawling with revulsion watching that C# coding in action and our thoughts immediately jumped to how can we write as little code as possible in MonoDevelop should it actually ever become necessary to work with a Unity project.

So yeah, the end result of this exercise is a switch from “intense skepticism” to “downright loathing” of the prospect of ever having to code ourselves in this environment. But for those who don’t have a project with heavy coding needs, or are Windows people who are happy programming C#, first off we’re sorry for you, and second off yep Unity most likely actually is a good choice for you and this is a definitely worthwhile fast start on getting orientated with it. Thoroughly recommended!

Continue Reading →
Page 3 of 95 12345...»