hinterbu hinterbu - 22 days ago 8
iOS Question

How to show live camera preview as soon as iOS app launches?

I am following a tutorial on building a camera app here: https://www.appcoda.com/ios-programming-camera-iphone-app/

It is a simple app with an image view and two buttons, one to take a photo, the other to select a photo from the devices photo library.

So at the moment when I press on the Take Photo button, the camera appears and I can take a picture and so on.

But is there a way to show the live camera preview as soon as the app launches and opens without having to first press Take Photo explicitly? How would I trigger that in viewDidLoad, or elsewhere? Do I need to use AV Foundation?

At the moment my program is using the image picker controller to present the camera to the user using this code:

- (IBAction)takePhoto:(UIButton *)sender {

UIImagePickerController *picker = [[UIImagePickerController alloc] init];
picker.delegate = self;
picker.allowsEditing = YES;
picker.sourceType = UIImagePickerControllerSourceTypeCamera;

[self presentViewController:picker animated:YES completion:NULL];

}

Answer

Sorry for the short answer but yes, you need to use AVFoundation. There is no decent way to embed the UIImagePickerController to your view.

You could, of course, use -[UIViewController addChildViewController:] and then add the imagePickers view as subview into your viewController:

[[self view] addSubview:[pickerVC view]];

[self addChildViewController:pickerVC];
[pickerVC didMoveToParentViewController:self];

But to be honest, you might better implement the camera using AVFoundation, as the approach above might seem kinda "hackish" nowadays, as I personally think. Also you'd need to properly deal with auto layout and I don't really know, if the UIImagePickerViewController in particular likes to be treated like this. Keep in mind that these components are built for specific use cases and to serve a special purpose, not as usual subclassable, open solution like UIViewController

Comments