How to Set The Image Name When Saving to The Camera Roll

In principle, you can’t. But in practice, there is a way… Read on to find out.

iOS names the image IMG_<num> to avoid file name clashes. There is no way to change that from your app.
However, if the user later imports an image to iPhoto, then the metadata of the image will determine its title, description, and keywords.
If the user then exports the image to file, iPhoto can use the title for the name of the exported file. (Instructions for doing that are down below, after the code.)

Here is the code to set the metadata and save the image to the camera roll. The code below gets the image from the camera, but this isn’t necessary – the image can come from anywhere.

- (void) imagePickerController: (UIImagePickerController *)picker didFinishPickingMediaWithInfo: (NSDictionary *)info
    [self dismissViewControllerAnimated:YES completion:nil];
    UIImage *image = info[UIImagePickerControllerOriginalImage];
    NSMutableDictionary *metadata = info[UIImagePickerControllerMediaMetadata];

    // set image name and keywords in IPTC metadata
    NSString *iptcKey = (NSString *)kCGImagePropertyIPTCDictionary;
    NSMutableDictionary *iptcMetadata = metadata[iptcKey];
    iptcMetadata[(NSString *)kCGImagePropertyIPTCObjectName] = @"Image Title";
    iptcMetadata[(NSString *)kCGImagePropertyIPTCKeywords] = @"some keywords";
    metadata[iptcKey] = iptcMetadata;

    // set image description in TIFF metadata
    NSString *tiffKey = (NSString *)kCGImagePropertyTIFFDictionary;
    NSMutableDictionary *tiffMetadata = metadata[tiffKey];
    tiffMetadata[(NSString *)kCGImagePropertyTIFFImageDescription] = @"Description for image"; // only visible in iPhoto when IPTCObjectName is set
    metadata[tiffKey] = tiffMetadata;

    // save image to camera roll
    ALAssetsLibrary library = [[ALAssetsLibrary alloc] init];
    [library writeImageToSavedPhotosAlbum:image.CGImage metadata:metadata completionBlock:nil];

Now the user can import the images to iPhoto and get your programmed title, description, and keywords.

To export the images to files that have the same name as the image title, the user should choose File > Export and then change the File Name field to Use title.


Posted in Uncategorized | Tagged , , , | Leave a comment

Workaround for bug in [NSMutableIndexSet shiftIndexesStartingAtIndex:by:]

The Bug

Shifting an NSMutableIndexSet by a negative number will drop an index in some cases.

Example Code:

NSMutableIndexSet *set = [NSMutableIndexSet indexSetWithIndex:0];
[set addIndex:2];
[set shiftIndexesStartingAtIndex:1 by:-1];
NSLog(@"%@", set);

The set should contain 0-1 but instead contains only 1.

The Reason

NSIndexSet is a series of NSRange-s. If the shift method removes empty space between ranges, than they should become a single unified range. For example, if a set contains the range 1-2 and the range 5-6, and we do

[set shiftIndexesStartingAtIndex:3 by:-2];

then we should get a set with a single range 1-4.

However, the implementation of shiftIndexesStartingAtIndex:by: fails to unify ranges, and also assumes that separate ranges have at least one empty space between them. And so we get a set containing the ranges 1-1 and 3-4.

The Workaround

Luckily, the methods addIndex: and addIndexesInRange: do correctly unify ranges. And so the workaround is to first call one of these methods, and only then shift:

[set addIndexesInRange:NSMakeRange(3, 2)];
[set shiftIndexesStartingAtIndex:3 by:-2];
Posted in Uncategorized | Tagged , , | Leave a comment

Simple UIProgressHUD replacement

The private API UIProgressHUD shows an activity indicator (spinner) over a shaded round rect. Although you can use fancy and flexible replacements like MBProgressHUD, there is a simpler way if you don’t need all the extra functionality: Take a regular UIActivityIndicatorView and add a partly transparent UIView behind it.

The simplest is to subclass of UIActivityIndicatorView so you can use it like any activity indicator.

The interface file:

//  ActivityHUD.h
#import <UIKit/UIKit.h>

@interface ActivityHUD : UIActivityIndicatorView
- (ActivityHUD *)initInView:(UIView *)view;

And the implementation file:

//  ActivityHUD.m
#import "ActivityHUD.h"
#import <QuartzCore/QuartzCore.h>

@implementation ActivityHUD

- (ActivityHUD *)initInView:(UIView *)view
    self = [super initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
    if (self) {
        // add background view
        CGFloat border = self.bounds.size.height / 2;
        CGRect hudFrame = CGRectInset(self.bounds, -border, -border);
        UIView *hud = [[UIView alloc] initWithFrame:hudFrame];
        hud.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.67];
        hud.layer.cornerRadius = border;
        [self addSubview:hud];
        [self sendSubviewToBack:hud];

        // center in parent view
        [view addSubview:self]; = [self fromView:view];
    return self;


To use, init the ActivityHUD in a view, and later call startAnimating to show it, and stopAnimating to hide.

Posted in Uncategorized | Leave a comment

The Three Underscores Idiom

#define ___
// defines three underscores as nothing

This is something I learned on my first programming job (eons ago…) and found useful but underused.

Useful for what? To solve the persistent tension between the robustness of single-exit point and the complexity of using extra state variables and state checking code.

Let me show you what I mean.

Continue reading

Posted in Uncategorized | Tagged , , | 1 Comment

Dynamic UIActionSheet

Some actions may sometimes have more than one possible target, and other times only one.

For example: Calling a contact. If the contact has just one phone number, you openURL with it and you’re done. But if she has several numbers, you want to open a UIActionSheet to let the user choose which number to call.

Or picking an image. If you’re running on a camera-less iPod, you just show a UIImagePickerController to pick from the photo library. But with a camera, and maybe an existing image to delete, you’ll want to show an action sheet to choose the actual action that your “Photo” button performs.

So you need to do two things:

  1. Decide whether to show an action sheet at all or just do the one possible action.
  2. If you need an action sheet, fill it dynamically with the possible targets for action.

The code to do that doesn’t have to be complicated. It can actually be as simple as this:

@interface MyViewController() : <UIActionSheetDelegate> {
	NSArray *possibleTargets; // action sheet buttons go here

@implementation MyViewControllerMyViewController

- (IBAction)selectTargetForAction:(id)sender
    possibleTargets = SomeWayToFindPossibleTargets();

    if ([possibleTargets count] == 1) {
        // just call the one number, or show the one image picker
        [self doAction:[possibleTargets lastObject]];
    else if ([possibleTargets count] > 1) {
        // show a dynamically filled action sheet
        UIActionSheet *targetsSheet =
            [[UIActionSheet alloc] initWithTitle:__(@"Select")
                cancelButtonTitle:nil // since we want it last
                otherButtonTitles:nil]; // since we can't hard-code them
        for (NSString *target in possibleTargets) {
            [targetsSheet addButtonWithTitle:__(target.title)];
        targetsSheet.cancelButtonIndex = [targetsSheet addButtonWithTitle:__(@"Cancel")];
        [targetsSheet showInView:self.view];

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
    if (buttonIndex != actionSheet.cancelButtonIndex) {
        [self doAction:[possibleTargets objectAtIndex:buttonIndex]];



  1. The @interface code above is part of the .m file, as described in my earlier post How to Keep Your Protocols Private.
  2. If you’re puzzled by the meaning of __(@"String") then see my earlier post on How To Make NSLocalizedString Fun To Use.
  3. The objects in possibleTargets can hold a selector (SEL) of the actual method to be executed, or they can hold just relevant data for the action (like a phone number to call).
Posted in Uncategorized | Tagged , , , | Leave a comment

Reordering a UITableView

I like the simple and straightforward interface of the edit reminders inline, and add a reminder by tapping and typing in the next empty line. So I wrote a UITableViewController subclass that does just that, but adds Edit mode with reordering.

Coding reordering requires implementing methods from both of the two entangled protocols UITableViewDataSource and UITableViewDelegate.

In UITableViewDataSource we have the methods:
tableView:commitEditingStyle:forRowAtIndexPath: (for insert and delete)
tableView:canMoveRowAtIndexPath: (for reorder)
tableView:moveRowAtIndexPath:toIndexPath: (for reorder)

And in UITableViewDelegate:
tableView:editingStyleForRowAtIndexPath: (for insert and delete)
tableView:targetIndexPathForMoveFromRowAtIndexPath:toProposedIndexPath: (for reorder)

The UITableViewDelegate methods are not strictly necessary in the simplest case where all rows are deletable, no row is insertable, and all rows are reorderable. In fact, in this simplest case you don’t need canMoveRowAtIndexPath either, only this:

- (void)tableView:(UITableView *)tableView
    moveRowAtIndexPath:(NSIndexPath *)fromIndexPath
    toIndexPath:(NSIndexPath *)toIndexPath
    // Update the model with the change.
    // The view updates are already handled by UIKit.

But of course, if the last row (or the row past last) is an insert row, and is not reorderable, than you need to implement the other methods as well. You can get the code for that (along with the inline editable UITextField-s) at GitHub:

Posted in Uncategorized | Tagged , , , | Leave a comment

How to Keep Your Protocols Private

Don’t you just hate when a small change in the innards of your view controller forces you to change its header file just to conform to a delegate protocol? For example, adding emailing functionality requires you to implement the MFMailComposeViewControllerDelegate protocol and @import <MessageUI/MessageUI.h>. Talk about breaking encapsulation…

Thankfully, you can do that in your .m implementation file instead. (Even though Apple sample code doesn’t.) All you need to do is use the empty category:

// MyViewController.m
#import "MyViewController.h"
#import <MessageUI/MessageUI.h>

@interface MyViewController ()
    <MFMailComposeViewControllerDelegate> // privately conform to protocol
@property (nonatomic, strong) UIView *somePrivateSubview;

@implementation MyViewController
// synthesize and methods implementations

The empty category MyViewController () allows you to define private ivars, properties, methods, and even protocols – all in the privacy of your .m file, transparent to your clients.

Posted in Uncategorized | Tagged , , , , | Leave a comment

BadgeLabel – Simple UILabel-based Badge

I know, I know – not another badge class! But the thing is, the other badges laying around the net all seem overly complicated and too inflexible. So yes, I wrote another badge class. Luckily, it was really easy because I used the built-in capabilities of iOS, and it turned out very flexible and powerful, because, well, I used the built-in capabilities of iOS. No manual CoreGraphics drawing code, just automatic CALayer-s magic.

The basic badge is a UILabel whose underlying CALayer has a backgroundColor and cornerRadius:

#import <QuartzCore/QuartzCore.h> // don't forget!
// ...
UILabel *badge = [[UILabel alloc] init];
badge.layer.backgroundColor = [UIColor blueColor].CGColor;
badge.layer.cornerRadius = badge.bounds.size.height / 2;

Basically, that’s it. There are some adjustments needed to make sure the label leaves enough space around the text for the rounded corners, but that’s easily done with short overrides of textRectForBounds and drawTextInRect.

The nice thing is how easy it is to make app-icon style badges, with border, shadow and gloss:

  • For border simply set the layer’s borderColor and borderWidth.
  • For shadow set the layer’s shadowOpacity, shadowColor and shadowOffset.
  • For gloss add a CAGradientLayer sublayer.

It’s that simple. And even better: animatable!

You can get the code, along with a style BadgeTableViewCell and a demo app, at GitHub:

Posted in Uncategorized | Tagged , , , | Leave a comment

Render UIView to UImage

There’s a simple way to render a UIView into a UIImage: use the view’s layer, and render it into a bitmap graphic context. Here is the code, phrased as a UIView category:

#import "UIView+RenderUIImage.h"
#import <QuartzCore/QuartzCore.h>

@implementation UIView (RenderUIImage)

- (UIImage *)renderAsImage
    // setup context
    UIGraphicsBeginImageContextWithOptions(self.bounds.size, NO, 0.0f); // use same scale factor as device
    CGContextRef c = UIGraphicsGetCurrentContext();

    // render view
    [self.layer renderInContext:c];

    // get reslting image
    UIImage *result = UIGraphicsGetImageFromCurrentImageContext();
    return result;


Just remember to link the QuartzCore.framework and you’re good to go.

Posted in Uncategorized | Tagged , , , | Leave a comment

How To Make NSLocalizedString Fun To Use

To localize apps (which means: to make them work in other languages) you need to avoid using plain @”strings” and instead use the one of the tedious functions NSLocalizedString, NSLocalizedStringFromTable, or NSLocalizedStringFromTableInBundle, that take two to four arguments. Horror.

I mean, any sane programmer will get a headache from replacing a simple @"Great!" with this:

NSLocalizedStringFromTable(@"Great!", @"Messages", nil)

So I took a leaf from WordPress, and shortened the calls:

#define __(str) NSLocalizedStringFromTable(str, @"Messages", nil)
#define __d(str, description) NSLocalizedStringFromTable(str, @"Messages", description)

Now localization is easy and fun: I simply type


and the localization code is taken care of by the C pre-processor. Mission accomplished.

Posted in Uncategorized | Tagged , , , , | Leave a comment