Populate Simulator’s Photo Library

Summary

iOS programs can easily access the Photo Library. The library on the iOS simulator is initially empty. Here’s how you add some sample media.

Introduction

It’s easy to write iOS programs that manipulate the contents of the user’s Photo Library. You can use UIImagePicker, or if you need more control, (under iOS 4) you can use the AssetsLibrary framework. When it comes times to develop, test, and debug those programs, it would be nice to use pictures in the simulator’s Photo Library. But, as shipped by Apple, the simulator’s Photo Library is empty.

It’s easy to find plenty of misinformation on the net for adding images to the library, but in my experiments, just dropping files into place in the Finder doesn’t work reliably for all versions of the simulator, and for all versions of the simulated iOS. What does work reliably is having a small sample iOS app that writes to the Photo Library.

The Method

Dragging a Folder

Dragging a folder from the Finder into your Xcode project sounds easy, but there are some gotchas:

In the Finder, copy the folder of Images into your Xcode project’s Finder folder.

Then, drag the copy into your Xcode project’s list of files panel.

Make sure you select the radio button: “Create Folder References for Any Added Folders”. This will cause the folder to get copied into your application, without Xcode altering the contents, or removing the folder structure.

The Code

Here’s the code to populate the Photo Library

- (void)image:(UIImage *)image
    didFinishSavingWithError:(NSError *)error
                 contextInfo:(void *)contextInfo {
  if (error) {
    NSLog(@"%@", error);
  }
}

- (void)debugWritePictures {
  NSBundle *mainBundle = [NSBundle mainBundle];
  NSArray *paths = [mainBundle pathsForResourcesOfType:@"jpg" inDirectory:@"Sample"];
  for (NSString *path in paths) {
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    UIImage *image = [[[UIImage alloc] initWithContentsOfFile:path] autorelease];
    if (image) {
      SEL sel = @selector(image:didFinishSavingWithError:contextInfo:);
      UIImageWriteToSavedPhotosAlbum(image, self, sel, NULL);
    }
    [pool release];
  }
}

Concluding words

Photo Library will happily make an additional copy of your sample folders’s images and video every time you run this. So run it once, unless you want lots of duplicate images in your photo library. Keep your loader app around, so you can be fearless about resetting the simulator whenever you want. Remember that different versions of the simulated iOS may store their images in different places, so check first: set the simulator to iOS version N, and check using its Photo Library application to see if you’ve already populated this versions’s library.