I am using swift 3. I'm trying to make a custom camera. But no matter how many tutorials I follow, or many of apple documentations, There's always an error.
class ViewController: UIViewController, UIImagePickerControllerDelegate {
@IBOutlet var cameraView: UIView!
var captureSession : AVCaptureSession?
var stillImageOutput : AVCaptureStillImageOutput?
var previewLayer : AVCaptureVideoPreviewLayer?
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
captureSession = AVCaptureSession()
captureSession?.sessionPreset = AVCaptureSessionPreset1920x1080
let backCamera = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeVideo)
let error : NSError?
do {
let input = try! AVCaptureDeviceInput (device: backCamera)
if (error == nil && captureSession?.canAddInput(input) != nil) {
captureSession?.addInput(input)
stillImageOutput = AVCaptureStillImageOutput()
stillImageOutput?.outputSettings = [AVVideoCodecKey: AVVideoCodecJPEG]
if (captureSession?.canAddOutput(stillImageOutput) != nil) {
captureSession?.addOutput(stillImageOutput)
previewLayer = AVCaptureVideoPreviewLayer (session: captureSession)
previewLayer?.videoGravity = AVLayerVideoGravityResizeAspect
previewLayer?.connection.videoOrientation = AVCaptureVideoOrientation.portrait
cameraView.layer.addSublayer(previewLayer!)
captureSession?.startRunning()
}
}
} catch {
}
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
previewLayer?.frame = cameraView.bounds
}
on this line, if (error == nil && captureSession?.canAddInput(input) != nil) {
, there is an error saying that the constant "error" has been used before initialized. I don't really understand this. Thank you in advance.
As the error message states, you are using error
before initializing it. You can fix this by initializing it with nil
:
let error: NSError? = nil
or even better:
let error: Error? = nil
Actually, you do not ever use error
, so you can simply remove it:
...
//let error : NSError? delete this line
do {
...
if (/* error == nil && delete this */captureSession?.canAddInput(input) != nil) {