Skip to content

Instantly share code, notes, and snippets.

@timd
Created April 6, 2012 07:24
Show Gist options
  • Save timd/2317906 to your computer and use it in GitHub Desktop.
Save timd/2317906 to your computer and use it in GitHub Desktop.
Simulator-safe method for using the hardware camera on iOS Simulators
-(void)takeSimulatorSafePhotoWithPopoverFrame:(GCRect)popoverFrame {
// Prerequisites:
//
// Class requires two properties to be defined:
//
// @property (nonatomic, strong) UIImagePickerController *imagePicker;
// @property (nonatomic) BOOL usingPopover;
// Load the imagePicker
self.imagePicker = [[UIImagePickerController alloc] init];
// Set the sourceType to default to the PhotoLibrary and use the ivar to flag that
// it will be presented in a popover
UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
self.usingPopover = YES;
// Check if the camera is available - if it is, reset the sourceType to the camera
// and indicate that the popover won't be used.
if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
sourceType = UIImagePickerControllerSourceTypeCamera;
self.usingPopover = NO;
}
// Set the sourceType of the imagePicker
[self.imagePicker setSourceType:sourceType];
// Set up the other imagePicker properties
self.imagePicker.allowsEditing = NO;
self.imagePicker.delegate = self;
// If the sourceType isn't the camera, then use the popover to present
// the imagePicker, with the frame that's been passed into this method
if (sourceType != UIImagePickerControllerSourceTypeCamera) {
self.popover = [[UIPopoverController alloc] initWithContentViewController:self.imagePicker];
self.popover.delegate = self;
[self.popover presentPopoverFromRect:popoverFrame inView:self.view permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
} else {
// Present a standard imagePicker as a modal view
[self presentModalViewController:imagePicker animated:YES];
}
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
// This UIIMagePickerController delegate method is called by the image picker when
// it's dismissed as a result of choosing an image from the Photo Library,
// or taking an image with the camera
UIImage *takenImage = [info objectForKey:UIImagePickerControllerOriginalImage];
// Do whatever is required with the image here
// ...
// Get rid of the imagePicker, either by dismissing the popover...
if (self.usingPopover) {
[self.popover dismissPopoverAnimated:YES];
} else {
// ...or dismissing the modal view controller
[self dismissModalViewControllerAnimated:YES];
}
}
@joshdance
Copy link

I used some ideas from this to make my app simulator safe. Thanks.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment