twostraws / CodeScanner

A SwiftUI view that is able to scan barcodes, QR codes, and more, and send back what was found.
MIT License
1.05k stars 300 forks source link

Hiding code scanner from view does not release the camera #121

Open epoberezkin opened 11 months ago

epoberezkin commented 11 months ago

Closing the containing sheet does release the camera though.

The trick that works to re-initialise the camera on re-appearance (https://github.com/twostraws/CodeScanner/issues/120) does not help camera to disappear.

Is it something that can be done with or without library change? Maybe expose some method to disable the camera?

dev4justice commented 6 months ago

I just noticed a similar case as well:

Steps to reproduce:

  1. Open a view that has the camera and wait for the camera session to be started
  2. Navigate to another app (slide at the bottom or receive a call)
  3. When you come back to the app, quickly switch to another tab that doesn't have the camera screen
  4. After some time the camera session starts even though the view is no longer visible

Possible fix: Remove if captureSession?.isRunning == true { check from ScannerViewController.swift's viewDidDisappear. Why? Calling self.captureSession?.startRunning() from setupSession() hasn't completed yet before we switch to another screen, which results in isRunning returning false.

Or better refactor the state management with an enum instead of depending on multiple booleans, something like:

enum CameraSessionState {
  case stopped
  case requestedToStart(Run?)
  case running
  case interrupted
}

Thinking about it a bit more, is there a memory leak that's keeping the session? 🤔