如何使用 UIImagePickerControllerDelegate 在 vi​​ewDidLoad 上启动相机?

How to launch camera on viewDidLoad with UIImagePickerControllerDelegate?

我在 Swift 中有一个新的 iOS 应用程序,我试图在应用程序启动后立即显示相机。在我的视图控制器中,我有一个 UIView 对象,我试图用相机填充它。

我的视图控制器中的代码在 viewDidLoad 方法中调用 UIImagePickerController 但没有任何反应。

这是代码,知道为什么没有任何反应吗?相机不是应该在使用此代码启动应用程序时打开吗?

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:如果我在情节提要中添加一个按钮,将其连接到代码并将 viewDidLoad 中的代码放入其中,当按钮时相机工作被点击:

@IBAction func presentImagePicker(sender: AnyObject) {

    if UIImagePickerController.isCameraDeviceAvailable( UIImagePickerControllerCameraDevice.Front) {
        imagePicker.delegate = self
        imagePicker.sourceType = UIImagePickerControllerSourceType.Camera
        presentViewController(imagePicker, animated: true, completion: nil)
    }
}

我知道相机可以工作,但如何让它在不按按钮的情况下工作?

这是适合您的解决方案。

以这种方式将您的代码放入 viewDidAppear 方法中:

override func viewDidAppear(animated: Bool) {

    if UIImagePickerController.isCameraDeviceAvailable( UIImagePickerControllerCameraDevice.Front) {
        imagePicker.delegate = self
        imagePicker.sourceType = UIImagePickerControllerSourceType.Camera
        presentViewController(imagePicker, animated: true, completion: nil)
    }
}

这将在您的应用程序启动时加载相机。

尝试在 viewDidLoad 中这样做是行不通的,因为它是在首次创建视图之后调用的,并且此时视图不是任何其他视图的子视图。

override func viewDidLoad() {

 if UIImagePickerController.isCameraDeviceAvailable( UIImagePickerControllerCameraDevice.Front) {
    imagePicker.delegate = self
    imagePicker.sourceType = UIImagePickerControllerSourceType.Camera
    presentViewController(imagePicker, animated: true, completion: nil)
 }
}