class CameraClass: NSObject, AVCaptureFileOutputRecordingDelegate {
var session = AVCaptureSession()
var videoDeviceInput: AVCaptureDeviceInput?
var movieOutput = AVCaptureMovieFileOutput()
This class inherits from NSObject
and conforms to AVCaptureFileOutputRecordingDelegate
, enabling it to respond to recording events.
The session and outputs are declared here.
override init() {
super.init()
prepare()
}
The initializer calls prepare()
to request camera access and configure the session once permission is granted.
func prepare() {
AVCaptureDevice.requestAccess(for: .video) { granted in
if granted {
print("Camera access granted")
DispatchQueue.main.async {
self.setupSession()
}
} else {
print("Camera access denied")
}
}
}
Requests video permission. If granted, proceeds to setup the capture session on the main thread.
private func setupSession() {
session.beginConfiguration()
guard let camera = AVCaptureDevice.default(for: .video) else {
print("No camera found")
session.commitConfiguration()
return
}
Starts configuration. Attempts to access the default video camera. If unavailable, ends configuration early.
do {
let input = try AVCaptureDeviceInput(device: camera)
if session.canAddInput(input) {
session.addInput(input)
videoDeviceInput = input
}
Creates an input from the camera device and adds it to the session if allowed.
if session.canAddOutput(movieOutput) {
session.addOutput(movieOutput)
}
Adds a video file output to the session.
session.commitConfiguration()
session.startRunning()
} catch {
print("Error setting up camera: \(error)")
session.commitConfiguration()
}
}
Commits the session configuration and starts the session. Catches and prints any setup errors.
func startRecording(to fileURL: URL) {
if !movieOutput.isRecording {
movieOutput.startRecording(to: fileURL, recordingDelegate: self)
}
}
Begins recording to a specified URL if the output is not already recording.
func stopRecording() {
if movieOutput.isRecording {
movieOutput.stopRecording()
}
}
Stops the recording session if it is active.
func fileOutput(_ output: AVCaptureFileOutput,
didFinishRecordingTo outputFileURL: URL,
from connections: [AVCaptureConnection],
error: Error?) {
if let error = error {
print("Recording error: \(error)")
} else {
print("Video saved to: \(outputFileURL)")
}
}
This delegate method is triggered when recording finishes. It checks for errors and prints the location of the saved video.