Localizing attributed strings on iOS

In an iOS app, localization can be especially difficult when dealing with attributed strings. Fairly often, designers request something like:

Read our Terms of Service, Privacy Policy, or contact us with any questions.

or like:

Searching for burgers in SOMA, San Francisco, CA:

The golden rule of localized strings is to treat them as atomic units:

  • Never concatenate strings to form sentences. Many languages have different sentence structure or gender rules than English and you cannot just substitute a single word or phrase in for any other.
  • Never use substrings for searching in an original string. If you depend on the standalone translation of “Privacy Policy” matching the sentence version, you will likely find translators do not understand this intent. You may also find the same search term multiple times (imagine if the user searched for “Search”).

Often these complexities are cited as reasons to avoid localization. But, unless you have geographic constraints, you will find a substantially larger audience with a localized application.

ZSWTappableLabel and ZSWTaggedString are two open-source libraries I have released to help solve these problems.

ZSWTappableLabel makes links inside your attributed strings tappable, as the name suggests. It’s a UILabel subclass which does not do any drawing itself, making it fast and easy.

ZSWTaggedString is the powerhouse. It transforms an HTML-like syntax into an attributed string. You can read more about the syntax and advanced usage on its GitHub page, but here’s how you might use it for the examples above:

Read our <i><tos>Terms of Service</tos></i>, <i><privacy>Privacy Policy</privacy></i>, or <i><contact>contact us</contact></i> with any questions. Searching for <term>%@</term> in <location>%@</location>:
Code language: HTML, XML (xml)

In my experience, localizers1 are familiar enough with HTML to have no issues with localizing these strings. By marking the regions you intend to be visually distinct, they can more easily understand your intent, producing better localizations.

While on the subject, here are a few best practices for localization in iOS:

  • To handle the current locale changing, or the dynamic type setting changing, reload your UI when observing:
    • NSCurrentLocaleDidChangeNotification
    • UIContentSizeCategoryDidChangeNotification
  • To represent dates, durations, distances, lengths, etc., use an appropriate formatter.
  • To create your own date formats, use +dateFormatFromTemplate:options:locale: on NSDateFormatter. Remember that these need recreating if the locale changes.
  • To combine a first and last name, use ABPersonGetCompositeNameFormatForRecord with a temporary ABPersonRef, or use the new NSPersonNameComponentsFormatter.
  • For sending non-user-facing data to a server, use en_US_POSIX as your locale.

    Read more tips and tricks at NSHipster about NSLocalizedString and NSLocale.

  1. If you’re looking for recommendations on localization, working with Applingua has always been wonderful. 

Saving optimal JPEGs on iOS

Conventional wisdom for creating a JPEG version of a UIImage is first to turn it into an NSData and immediately write it to disk like so:

NSData *jpegRepresentation = UIImageJPEGRepresentation(image, 0.94); [jpegRepresentation writeToFile:outputURL.path atomically:NO];
Code language: Objective-C (objectivec)

Most of the time this is exactly right. However, if file size is important, Image IO is a great alternative. It is a powerful system framework to read and write images, and produces smaller files at the same compression level.

Why Image IO?

A project I am working on requires uploading photos en masse. Low upload bandwidth makes file size a limiting factor, so I sought out ways to reduce it.

I put together a test project to find the differences between the two methods. The results are pretty interesting:

  • Image IO files are on average 20% (but up to 30%) smaller1.
  • Image IO takes about 2x longer.

The only discernable visual difference is the grain in the images, but even that is minor. Here’s a diff between two versions of the original photo. The changes are nearly all in the grain.

A diff between the two image output types

Using Image IO

First, you’ll need to add two new framework dependencies:

@import ImageIO; // to do the actual work @import MobileCoreServices; // for the type defines
Code language: Objective-C (objectivec)

When creating your JPEG file, the first step is to create a CGImageDestinationRef specifying where to write the result:

CGImageDestinationRef destinationRef = CGImageDestinationCreateWithURL((__bridge CFURLRef)outputURL, /* file type */ kUTTypeJPEG, /* number of images */ 1, /* reserved */ NULL);
Code language: Objective-C (objectivec)

Image IO is able to produce files of a few different types2 but my focus here is JPEGs. Next, we set up the properties of the output file, specifying a constant compression factor:

NSDictionary *properties = @{ (__bridge NSString *)kCGImageDestinationLossyCompressionQuality: @(0.94) }; CGImageDestinationSetProperties(destinationRef, (__bridge CFDictionaryRef)properties);
Code language: Objective-C (objectivec)

And, importantly, we specify what is to be written out:

CGImageDestinationAddImage(destinationRef, /* image */ image.CGImage, /* properties */ NULL);
Code language: Objective-C (objectivec)

And finally, we write it to disk and clean up the reference:

CGImageDestinationFinalize(destinationRef); CFRelease(destinationRef);
Code language: Objective-C (objectivec)

  1. The UIImage version has a color profile, while the Image IO version does not. However, running both files through Image Optim produces a 7% reduction on both, so I am choosing to ignore this difference. Afterall, you can’t remove the color profile anyway! 
  2. The following are possible types you can use, from the documentation:


    ConstantUTI type
    kUTTypeJPEG2000public.jpeg-2000 (OS X only)
    kUTTypePICTcom.apple.pict (OS X only)

Using the Xcode Structure menu

Xcode’s Editor > Structure menu has a few great actions:

Screenshot demonstrating where to find the menu item in Xcode

These actions all act on either your cursor position or selection.

Balance Delimiter

Normally you can double-click quotes, brackets, or parenthesis to select the matching character and all text in-between. The Balance Delimiter behaves similarly: it looks at your cursor position (or selection), finds the nearest pair and selects in-between.

This doesn’t have a default keyboard shortcut, but you can set one up in Xcode’s Key Bindings preferences. I set it to ⇧⌃I since I use it in similar ways to Re-Indent.

Re-Indent ⌃I

Objective-C is a fairly indentation-heavy language, and Xcode generally does a good job at indenting while you’re typing. However, if you’re pasting text or refactoring things can get pretty hairy, so let Xcode fix up your code for you with Re-Indent.

Shift Left ⌘[, Shift Right ⌘]

You can also indent manually using the Shift Left and Shift Right actions, which unindent or indent by one tab, respectively. They do exactly what they say on the tin.

Move Line Up ⌥⌘[, Move Line Down ⌥⌘]

These actions move your current line (or selection) up or down by one line. Simple, right? What’s really useful is that it is context-aware: they understand going in and out of control flow or blocks. Much faster than cutting, pasting and re-indenting each time.

Comment Selection ⌘/

Rather than wrapping your code in /* … */ and dealing with the conflicting multi-line comments you probably already have, simply select what you want to temporarily eliminate and hit the shortcut. Each line selected is then prefixed by //.

Error arguments in Objective-C

From the Programming with Objective-C (backup) overview from Apple:

When dealing with errors passed by reference, it’s important to test the return value of the method to see whether an error occurred, as shown above. Don’t just test to see whether the error pointer was set to point to an error.

and from the Error Handling Programming Guide (backup):

Success or failure is indicated by the return value of the method. Although Cocoa methods that indirectly return error objects in the Cocoa error domain are guaranteed to return such objects if the method indicates failure by directly returning nil or NO, you should always check that the return value is nil or NO before attempting to do anything with the NSError object.

For example, let’s say we’re executing a fetch request:

NSError *error = nil; NSFetchRequest *request = /* … */; NSArray *objects = [context executeFetchRequest:request error:&error];
Code language: Objective-C (objectivec)

To test if the fetch was successful, we must do:

if (objects) { // hooray! } else { NSLog(@"Got an error: %@", error); }
Code language: Objective-C (objectivec)

A method taking an NSError ** does not guarantee how it is used when successful. In this case, even a successful method call may end up with error set to something other than nil.

Cleaning up old git branches

My local git repository is full of branches which have long-since been merged: code review, one-off features, and quick bug fixes add up really quickly. Deleting these branches is cumbersome.

Complaining on Twitter proved really fruitful:

There’s also `git branch –merged`, which you could pipe to xargs (assuming you can remember the syntax, which I never can.) — @bjhomer

Of course, he’s right, so finding and deleting them is easy. The end result is this wonderful snippet, which deletes all merged branches:

git branch --merged origin/master | grep -v master | xargs git branch -d
Code language: Bash (bash)

The text spam after it executes can only be described as cathartic.

Portable encrypted backups

To keep track of the ever-growing array of passwords and private data, I use 1Password, which I could not recommend more.

There’s a problem though: what if I lose access to my database? I’ve toyed with a few options in the past, including uploading it to Dropbox or Google Drive, but these are services for which I’ve enabled multi-factor authentication, and require internet access.

For a few years now, Macbook Pros have included an SD slot for photographers. Or, as it turns out, everybody!

I bought a Transcend SD card with a decently-useful 16GB capacity for about $10. As of OS X 10.8, you can format any disk to be encrypted. Match made in heaven.

Going from the stock card to an encrypted version is easy, but does involve making the disk Mac-only:

  1. Launch Disk Utility from /Applications/Utilities
  2. Select the SD card from the source list and choose “Partition.”
  3. When repartitioning the drive, choose “Options…” and format using GPT.
  4. Erase the newly-created partition with the “Mac OS Extended (Journaled, Encrypted)” option.

With a tiny, portable, encrypted disk, there’s a lot of cool things you can back up. I currently save:

  • My 1Password and system keychains.
  • The database for Authy, which is like Google Authenticator, backed up via iExplorer.
  • Copies of my source code repositories.
  • Public and private SSH keys.

I’ll find more uses as time goes on. Right now it’s a manual process to update, but this is more of an emergency backup: I use Arq for my normal backup needs.

Incrementing with a bitmask

Bitmasks are fun. There’s lots of little tricks you can do with them. A common situation is checking for the presence of a flag among elements in a linked list, or some similar data structure. I came across a trick a few years ago that makes it drop-dead simple.

Let’s say we needed to check for AUsefulFlag in the flags element of each node, and total how many elements in the linked list had the flag.

uint64_t count = 0; for(Node *iter = head; iter != NULL; iter = iter->next) { count += !!(iter->flags & AUsefulFlag); }
Code language: C++ (cpp)

After execution, count is the number of items which have AUsefulFlag set.

Double-not (!!) is one of those useful operations which are especially useful with bitmasks. It may require a double-take at first, but it behaves exactly how you’d think.

!! of 1 is 1. !! of 0 is 0. In fact, !! of any true value evaluates to 1, so we can use it to transform something like 0b00001000 to simply 1 and increment by that value.