AVCaptureSession 是应用程序中处理摄像头输入的重要类之一。在正确的处理方案下,我们可以保证 AVCaptureSession 在应用程序生命周期中得到最佳的利用,从而提高应用程序的性能和展现。以下是一些解决方案:
class SessionManager {
static let shared = SessionManager()
var session: AVCaptureSession?
func startSession() {
session = AVCaptureSession()
// configure the session here
session?.startRunning()
}
func stopSession() {
session?.stopRunning()
session = nil
}
}
class Component {
private weak var session: AVCaptureSession?
init(session: AVCaptureSession) {
self.session = session
}
func addInput(_ input: AVCaptureInput) {
if session?.canAddInput(input) == true {
session?.addInput(input)
}
}
func addOutput(_ output: AVCaptureOutput) {
if session?.canAddOutput(output) == true {
session?.addOutput(output)
}
}
func removeInput(_ input: AVCaptureInput) {
session?.removeInput(input)
}
func removeOutput(_ output: AVCaptureOutput) {
session?.removeOutput(output)
}
}