Before iOS 10 came out I was using the following code to get the video and audio capture for my video recorder:
for device in AVCaptureDevice.devices()
{
Swift 4, iOS 10+ and Xcode 10.1 replaces
if let cameraID = AVCaptureDevice.default(.builtInWideAngleCamera, for: .video, position: .front)?.localizedName {
//cameraID = "Front Camera"
}
with AVCaptureDevice.DiscoverySession implementation
if let cameraID = AVCaptureDevice.DiscoverySession.init(deviceTypes: [AVCaptureDevice.DeviceType.builtInWideAngleCamera], mediaType: .video, position: .front).devices.first?.localizedName{
//cameraID = "Front Camera"
}
Need to wrap it with #available(iOS 10,*) check.
Simplified:
func getCamera(with position: AVCaptureDevice.Position) -> AVCaptureDevice? {
let deviceDescoverySession = AVCaptureDevice.DiscoverySession(deviceTypes: [.builtInDualCamera], mediaType: .video, position: .unspecified)
return deviceDescoverySession.devices.first(where: { $0.position == position })
}
// and you can use like that:
guard let device = getCamera(with: .back) else { return }
05/2019 :
//video
self.session = AVCaptureSession()
guard
let videoDeviceInput = try? AVCaptureDeviceInput(device: device!),
self.session!.canAddInput(videoDeviceInput)
else { return }
self.session!.addInput(videoDeviceInput)
//audio
guard
let audioDeviceInput = try? AVCaptureDeviceInput(device: mic!),
self.session!.canAddInput(audioDeviceInput)
else { return }
self.session!.addInput(audioDeviceInput)
example: iOS 11 Swift 4
override func viewDidLoad() {
super.viewDidLoad()
// Get the back-facing camera for capturing videos
// AVCaptureDevice.default(.builtInWideAngleCamera, for: AVMediaType.video, position: .back)
let deviceDiscoverySession = AVCaptureDevice.default(.builtInWideAngleCamera, for: AVMediaType.video, position: .back)
guard let captureDevice = deviceDiscoverySession else {
print("Failed to get the camera device")
return
}
do {
// Get an instance of the AVCaptureDeviceInput class using the previous device object.
let input = try AVCaptureDeviceInput(device: captureDevice)
// Set the input device on the capture session.
captureSession.addInput(input)
} catch {
// If any error occurs, simply print it out and don't continue any more.
print(error)
return
}
// Initialize the video preview layer and add it as a sublayer to the viewPreview view's layer.
videoPreviewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
videoPreviewLayer?.videoGravity = AVLayerVideoGravity.resizeAspectFill
videoPreviewLayer?.frame = view.layer.bounds
view.layer.addSublayer(videoPreviewLayer!)
// Start video capture.
captureSession.startRunning()
You can get the front camera with the following:
AVCaptureDevice.default(.builtInWideAngleCamera, for: AVMediaType.video, position: .front)
The back camera:
AVCaptureDevice.default(.builtInWideAngleCamera, for: AVMediaType.video, position: .back)
And the microphone:
AVCaptureDevice.default(.builtInMicrophone, for: AVMediaType.audio, position: .unspecified)