Search code examples
iosswiftuiimagepickercontroller

How to check if the top most view controller is an ImagePickerController


I use the following to check for the top most view controller. I need to check if the top view controller is an ImagePickerController

guard let window = UIApplication.shared.windows.first(where: \.isKeyWindow) else { return }
        
guard let topVC = window.topViewController() else { return }

if topVC.isKind(of: ImagePickerController.self) {
    // ...
}

but I get an error enter image description here

How can I check if the top vc has/is an imagePicker presented?

extension UIWindow {
    func topViewController() -> UIViewController? {
        var top = self.rootViewController
        while true {
            if let presented = top?.presentedViewController {
                top = presented
            } else if let nav = top as? UINavigationController {
                top = nav.visibleViewController
            } else if let tab = top as? UITabBarController {
                top = tab.selectedViewController
            } else {
                break
            }
        }
        return top
    }
}

Solution

  • You are setting ImagePickerController.self but the class name is UIImagePickerController

    You can use like this

    if let imagePicker = UIApplication.shared.windows.first?.topViewController() as? UIImagePickerController {
     // Do your stuf
    }
    

    Or

    if topVC.isKind(of: UIImagePickerController.self) {
        // ...
    }
    

    Note: By using this you can not cast the top view controller as a UIImagePickerController. As it's designed by apple.

    You can use this and access the view controller by this.

    if let pickerHostClass = NSClassFromString("PUPhotoPickerHostViewController"), topVC.isKind(of: pickerHostClass) {
       topVC.view.alpha = 0.5
    }