Skip to content

Conversation

@Barba2k2
Copy link

Summary

  • Fixed crash on iOS where rootViewController was force-unwrapped during plugin registration when it was still nil
  • Changed viewController from a static stored property to a computed property that safely retrieves the root view controller
  • Uses UIWindowScene for modern iOS with fallback for older versions

Problem

The app crashed with "force unwrapped a nil value" at line 64 of SwiftFlutterBarcodeScannerPlugin.swift during plugin registration because rootViewController is not yet available at that point in the app lifecycle.

Solution

Changed the static viewController property to a computed property that lazily and safely fetches the root view controller when actually needed (not during registration).

public static var viewController: UIViewController? {
    if let windowScene = UIApplication.shared.connectedScenes.first as? UIWindowScene,
       let rootVC = windowScene.windows.first?.rootViewController {
        return rootVC
    }
    return UIApplication.shared.delegate?.window??.rootViewController
}

Copy link

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR fixes a critical iOS crash caused by force-unwrapping a nil rootViewController during plugin registration. The fix changes the viewController from a static stored property to a computed property that safely retrieves the root view controller when needed, with support for modern iOS using UIWindowScene and a fallback for older versions.

Changes:

  • Converted viewController from a stored property to a computed optional property that lazily retrieves the root view controller
  • Removed the force-unwrapped assignment in the register method that was causing the crash
  • Added safe unwrapping with guard statements at all usage sites of viewController

Reviewed changes

Copilot reviewed 1 out of 2 changed files in this pull request and generated 3 comments.

File Description
ios/Classes/SwiftFlutterBarcodeScannerPlugin.swift Changed viewController to a computed optional property with safe retrieval logic, removed crash-prone force unwrap in register method, and added guard statements at all usage points
example/pubspec.lock Updated transitive dependencies (meta and test_api) - routine dependency updates

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

@sonarqubecloud
Copy link

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant