             waitForLoadingIndicatorToDisappear(within: timeout)
         }
 
-        print("snapshot: \(name)") // more information about this, check out https://github.com/fastlane/fastlane/tree/master/snapshot#how-does-it-work
+        print("snapshot: \(name)") // more information about this, check out https://docs.fastlane.tools/actions/snapshot/#how-does-it-work
 
         sleep(1) // Waiting for the animation to be finished (kind of)
 
         #if os(OSX)
             XCUIApplication().typeKey(XCUIKeyboardKeySecondaryFn, modifierFlags: [])
         #else
-            let screenshot = app.windows.firstMatch.screenshot()
+            
+            guard let app = self.app else {
+                print("XCUIApplication is not set. Please call setupSnapshot(app) before snapshot().")
+                return
+            }
+            
+            guard let window = app.windows.allElementsBoundByIndex.first(where: { $0.frame.isEmpty == false }) else {
+                print("Couldn't find an element window in XCUIApplication with a non-empty frame.")
+                return
+            }
+
+            let screenshot = window.screenshot()
             guard let simulator = ProcessInfo().environment["SIMULATOR_DEVICE_NAME"], let screenshotsDir = screenshotsDirectory else { return }
             let path = screenshotsDir.appendingPathComponent("\(simulator)-\(name).png")
             do {

    }

    class func setLocale(_ app: XCUIApplication) {
        let path = cacheDirectory.appendingPathComponent("locale.txt")

        do {

                throw SnapshotError.cannotDetectUser
            }

            guard let usersDir = FileManager.default.urls(for: .userDirectory, in: .localDomainMask).first else {
                throw SnapshotError.cannotFindHomeDirectory
            }

            homeDir = usersDir.appendingPathComponent(user)
        #else
            #if arch(i386) || arch(x86_64)
                guard let simulatorHostHome = ProcessInfo().environment["SIMULATOR_HOST_HOME"] else {
                    throw SnapshotError.cannotFindSimulatorHomeDirectory
                }
                guard let homeDirUrl = URL(string: simulatorHostHome) else {
                    throw SnapshotError.cannotAccessSimulatorHomeDirectory(simulatorHostHome)
                }
                homeDir = URL(fileURLWithPath: homeDirUrl.path)
            #else
                throw SnapshotError.cannotRunOnPhysicalDevice
            #endif
        #endif
        return homeDir.appendingPathComponent("Library/Caches/tools.fastlane")
    }
