When you’re using the iPhone and iPad Simulators to run your development code, you’ll find that they have a significant limitation if you’re building apps that use hardware features like the camera.
If your code tries to use the camera on a Simulator device, it’ll crash – not altogether surprisingly because the Simulator doesn’t have a hardware camera. That gets painful pretty quickly.
As a workaround for a project that I’m working on, I figured it would be useful to have the option to select an image from the Simulator’s library in places where normally the camera would be the default option.
This will also come in useful for handling situations where the camera is already in use – you might have another app running in the background that hasn’t released the camera for some reason.
Here’s the two methods that handles this.
The first uses UIImagePicker'sisSourceTypeAvailable to check if there is a camera device available to use. If there isn’t, it presents a popover view containing the device’s Photo library from which an image can be selected. The image, whether chosen or taken, is made available to UIImagePickerController'sdidFinishPickingMediaWithInfo: method. Here you do whatever you need to do with the image, and then get rid of the popover if you’re using one.
It’s pretty straight-forward – you’ll need a couple of properties defined at the top of your class (one to hold a reference to the UIImagePickerController and another to hold a flag to indicate that you’re using a popover). Then use this takeSimulatorSafePhotoWithPopoverFrame: method whenever you want to take a photo. The method takes a single parameter – a CGRect frame for the popover, so you can place this accurately in your UI.
The second method is a UIImagePickerController delegate method that handles the image which is captured or chosen, then dismisses the popover if required.
Drop the first method in wherever you use the camera, and your code will work on the Simulator without crashing.