如何使用UIImagePickerControllerDelegate在viewDidLoad上启动相机?

时间:2015-02-27 05:03:47

标签: ios objective-c iphone swift camera

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

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

这是代码,任何想法为什么没有发生?使用此代码是否应该在应用程序启动时打开相机?

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
    }
}

更新:如果我在故事板上添加一个按钮,将其连接到代码并将viewDidLoad中的代码放入其中,单击按钮时相机就会工作:

@IBAction func presentImagePicker(sender: AnyObject) {

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

我知道相机可以正常工作,但如何在不按按钮的情况下使其工作?

2 个答案:

答案 0 :(得分:11)

以下是适合您的解决方案。

以这种方式将代码放在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中尝试这样做是不可行的,因为在首次创建视图后调用它,并且视图不是该点上任何其他内容的子视图。

答案 1 :(得分:0)

override func viewDidLoad() {

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