Copy func setupPreviewLayer () {
guard videoLayer == nil else { return }
if let videoLayer = passioSDK. getPreviewLayer () {
self.videoLayer = videoLayer
videoLayer.frame = view.bounds
DispatchQueue.main. async { [ weak self] in
self ? . view .layer. insertSublayer ( videoLayer, at : 0 )
}
}
}
Copy func startFoodDetection () {
setupPreviewLayer ()
DispatchQueue. global ( qos : .userInitiated ) . async { [ weak self] in
guard let self else { return }
let config = FoodDetectionConfiguration ( detectVisual : true ,
volumeDetectionMode : . none ,
detectBarcodes : true ,
detectPackagedFood : true )
passioSDK. startFoodDetection ( detectionConfig : config,
foodRecognitionDelegate : self ) { ready in
print ( "SDK was not configured correctly" )
}
}
}
Add a function to request authorization to use the camera and start recognition. Call the function from viewWillAppear
:
Copy func checkCameraAuthorizationAndStartDetection () {
if AVCaptureDevice. authorizationStatus ( for : .video ) == .authorized {
startFoodDetection ()
} else {
AVCaptureDevice. requestAccess ( for : .video ) { granted in
if granted {
DispatchQueue.main. async { [ weak self] in
self ? . startFoodDetection ()
}
} else {
print ( "The user didn't grant access to use camera" )
}
}
}
}
Copy override func viewWillAppear ( _ animated : Bool ) {
super. viewWillAppear ( animated )
checkCameraAuthorizationAndStartDetection ()
}
Copy func stopFoodDetection () {
passioSDK. stopFoodDetection ()
videoLayer ? . removeFromSuperlayer ()
videoLayer = nil
}
Copy override func viewWillDisappear ( _ animated : Bool ) {
super. viewWillDisappear ( animated )
stopFoodDetection ()
}