解决这个问题的一种方法是使用NSNotificationCenter观察UIApplicationDidEnterBackgroundNotification和UIApplicationWillEnterForegroundNotification通知,以在应用进入后台和返回前台时暂停和恢复AVCaptureSession的运行。
首先,在需要使用AVCaptureSession的类中,添加以下代码来观察进入后台和返回前台的通知:
// 添加观察者监听进入后台和返回前台的通知
NotificationCenter.default.addObserver(self, selector: #selector(appDidEnterBackground), name: UIApplication.didEnterBackgroundNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(appWillEnterForeground), name: UIApplication.willEnterForegroundNotification, object: nil)
然后,在同一个类中添加以下方法来处理进入后台和返回前台的操作:
@objc func appDidEnterBackground() {
// 进入后台时,暂停AVCaptureSession的运行
if captureSession.isRunning {
captureSession.stopRunning()
}
}
@objc func appWillEnterForeground() {
// 返回前台时,重新开始AVCaptureSession的运行
if !captureSession.isRunning {
captureSession.startRunning()
}
}
这样,当应用进入后台时,AVCaptureSession会停止运行;当应用返回前台时,AVCaptureSession会重新开始运行。
注意:在不再需要使用AVCaptureSession的类中(例如,当视图控制器被销毁时),记得要移除观察者,以避免内存泄漏:
// 移除观察者
NotificationCenter.default.removeObserver(self)
这样就可以保证在进入后台和返回前台时,AVCaptureSession会正确地暂停和恢复运行。