CodeScanner icon indicating copy to clipboard operation
CodeScanner copied to clipboard

Completion handler might be called during view update

Open fossil12 opened this issue 2 years ago • 2 comments

  1. Grant camera access for app
  2. Disable camera access
  3. Open view using a navigation link that contains the CodeScannerView which shows an alert using a state boolean if there is not camera access (see code below).

Expected: The alert appears Actual: No alert is shown and an error is logged: [SwiftUI] Modifying state during view update, this will cause undefined behavior. Workaround: Set the change to the alert bool in a new main actor task


Code to reproduce the issue:

// ContentView.swift

import SwiftUI

struct ContentView: View {
    var body: some View {
        NavigationView {
            NavigationLink("Show Detail") {
                DetailCameraView()
            }
        }
    }
}
// DetailCameraView.swift

import SwiftUI
import CodeScanner

struct DetailCameraView: View {
    
    @State private var showNoCameraAccess = false
    
    var body: some View {
        CodeScannerView(codeTypes: [.qr]) { result in
            switch result {
            case .success(_):
                print("Success")
            case .failure(_):
                // Task { @MainActor in // Workaround
                    showNoCameraAccess = true
                // }
            }
        }
        .alert("No Camera Access", isPresented: $showNoCameraAccess) {
            // OK button is shown by default
        }
    }
}

fossil12 avatar Jul 31 '23 12:07 fossil12

Can confirm this is happening for us too.

timlittlelabs avatar Jun 06 '24 13:06 timlittlelabs