How to launch camera on viewDidLoad with UIImagePickerControllerDelegate?
camera, ios, iphone, objective-c, swift
Solution
Here is the solution for you.
Put your code in `viewDidAppear` method this way:
override func viewDidAppear(animated: Bool) {
if UIImagePickerController.isCameraDeviceAvailable( UIImagePickerControllerCameraDevice.Front) {
imagePicker.delegate = self
imagePicker.sourceType = UIImagePickerControllerSourceType.Camera
presentViewController(imagePicker, animated: true, completion: nil)
}
}
This will load camera when your app start.
Trying to do it in viewDidLoad won't work because that is called after the view is first created, and the view isn't a subview of anything else at that point.
Problem
I have a new iOS app in Swift where I'm trying to show the camera as soon as the app is launched. In my view controller I have a single `UIView` object which I try to fill with the camera. The code in my view controller calls `UIImagePickerController` in the `viewDidLoad` method but nothing happens. Here is the code, any idea why nothing happens? Isn't the camera supposed to open on app launch with this code? ``` import UIKit class ViewController: UIViewController, UINavigationControllerDelegate, UIImagePickerControllerDelegate { let imagePicker = UIImagePickerController() @IBOutlet weak var imageViewer: UIImageView! override func viewDidLoad() { super.viewDidLoad() if UIImagePickerController.isCameraDeviceAvailable( UIImagePickerControllerCameraDevice.Front) { imagePicker.delegate = self imagePicker.sourceType = UIImagePickerControllerSourceType.Camera presentViewController(imagePicker, animated: true, completion: nil) } else { println("no front camera available") } // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage!, editingInfo: [NSObject : AnyObject]!) { dismissViewControllerAnimated(true, completion: nil) imageViewer.image = image } } ``` UPDATE: if I add a button to the storyboard, connect it to the code and put the code from `viewDidLoad` in it, the camera works when the button is clicked: ``` @IBAction func presentImagePicker(sender: AnyObject) { if UIImagePickerController.isCameraDeviceAvailable( UIImagePickerControllerCameraDevice.Front) { imagePicker.delegate = self imagePicker.sourceType = UIImagePickerControllerSourceType.Camera presentViewController(imagePicker, animated: true, completion: nil) } } ``` I know that the camera works, but how to make it work without having to press a button?