# Start/Stop food detection

Add a function to setup the camera preview layer:

```swift
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)
        }
    }
}
```

Add the method `startFoodDetection()` This code will throw a missing delegate conformance error that we will resolve in the next step, ignore it for now.

```swift
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`:

```swift
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")
            }
        }
    }
}
```

```swift
override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    checkCameraAuthorizationAndStartDetection()
}
```

Create a function to stop Food Detection and call it from `viewWillDisappear`:

```swift
func stopFoodDetection() {
    passioSDK.stopFoodDetection()
    videoLayer?.removeFromSuperlayer()
    videoLayer = nil
}
```

```swift
override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)
    stopFoodDetection()
}
```

If at any point you need help from the Passio team, please reach out to us at **support@passiolife.com**
