Posted at

AVCaptureSessionDidStopRunningが呼ばれるタイミング

AVCaptureSessionのstopRunning()を呼ぶと、AVCaptureSessionDidStopRunningが発信される。これは普通の挙動。

しかし、AVCaptureSessionがrunnning状態で開放された時は呼ばれないので注意。

以下検証コード

import UIKit

import AVFoundation

class ViewController: UIViewController {

private var token: NSObjectProtocol? = nil
var camera: Camera? = Camera()

override func viewDidLoad() {
super.viewDidLoad()
let nc = NotificationCenter.default
token = nc.addObserver(forName: NSNotification.Name.AVCaptureSessionDidStopRunning, object: nil, queue: .main) { (_) in
print("stop")
}
camera?.start()
camera = nil
}
}

class Camera: NSObject {
lazy var session: AVCaptureSession = .init()
lazy var input: AVCaptureDeviceInput = try! AVCaptureDeviceInput(device: device)
lazy var device: AVCaptureDevice = AVCaptureDevice.default(for: .video)!
lazy var output: AVCaptureVideoDataOutput = .init()

override init() {
super.init()
session.addInput(input)
session.addOutput(output)
output.setSampleBufferDelegate(self, queue: .main)
}

func start() {
session.startRunning()
}

func stop() {
session.stopRunning()
}
}
extension Camera: AVCaptureVideoDataOutputSampleBufferDelegate {
func captureOutput(_ output: AVCaptureOutput, didDrop sampleBuffer: CMSampleBuffer, from connection: AVCaptureConnection) {

}

func captureOutput(_ output: AVCaptureOutput, didOutput sampleBuffer: CMSampleBuffer, from connection: AVCaptureConnection) {

}
}