1

I'm trying to make an app that uses the camera, but with the following code, it just shows a white screen. When the app opens, the camera should appear.

import UIKit
import AVFoundation
import Foundation

@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)


    do {

        let input = try! AVCaptureDeviceInput (device: backCamera)
        if (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
}

With this code, All I see is a white screen instead of the camera being used. Thank you.

DrPepperGrad
  • 361
  • 1
  • 4
  • 17

1 Answers1

0

So someone actually answered this, then deleted the answer. It said "you did not give permission". He was right.

How to enable this is by going to your info.plist(which can be found by: clicking your project with the blueprint next to it> going over to Targets and tapping your app>and looking at what should say "Custom iOS Target Properties".)

After getting here(info.plst), go to the bottom of the list and hover over the last one(which in my case was "required Device Capabilities". Click the plus button that shows up and name it "Privacy - Camera Usage Description". Type in the box next to it, "app name wants to use the camera for... [xyz]"

This should fix it. It fixed my problem. Got my reference from this post. NSCameraUsageDescription in iOS 10.0 runtime crash?

Community
  • 1
  • 1
DrPepperGrad
  • 361
  • 1
  • 4
  • 17