0

We have to upload an image into web service in a background thread. For example, I have a Home screen and Login screen. When I upload an image in home screen and navigate to the Login screen if I get a timeout error in home screen, I have to show an alert in Login screen.

NOTE : I have to call the background thread call a delegate method in the current view to display the alert instead of using UIAlertController in window root

To present alert on top of all views :

 func alertWindow(title: String, message: String) {
     DispatchQueue.main.async(execute: {
         let alertWindow = UIWindow(frame: UIScreen.main.bounds)
        alertWindow.rootViewController = UIViewController()
         alertWindow.windowLevel = UIWindowLevelAlert + 1

        let alert2 = UIAlertController(title: title, message: message, preferredStyle: .alert)
        let defaultAction2 = UIAlertAction(title: "OK", style: .default, handler: { action in
         })
        alert2.addAction(defaultAction2)

         alertWindow.makeKeyAndVisible()

           alertWindow.rootViewController?.present(alert2, animated: true, completion: nil)
     }) }
 Function calling:::::

     SharedClass.sharedInstance.alertWindow(title:"This your title",  message:"This is your message")



The above code is working fine but i have to show the alert in the current view using delegates how to do that?

HariKarthick
  • 1,369
  • 1
  • 19
  • 47
  • 1
    I can't see where is the problem... All you have to do is to call the delegate.whaterver inside `DispatchQueue.main.async` instead of presenting an alert... – Ahmad F Feb 18 '19 at 08:13

1 Answers1

2

Use this method to get the Top Most Controller in view heirarchy

func topViewController(controller: UIViewController? = UIApplication.shared.keyWindow?.rootViewController) -> UIViewController? {
        if let navigationController = controller as? UINavigationController {
            return topViewController(controller: navigationController.visibleViewController)
        }
        if let tabController = controller as? UITabBarController {
            if let selected = tabController.selectedViewController {
                return topViewController(controller: selected)
            }
        }
        if let presented = controller?.presentedViewController {
            return topViewController(controller: presented)
        }
        return controller
    }

and call it like this :

   topViewController()?.present(yourvc, animated: true, completion: nil)
Shahzaib Qureshi
  • 989
  • 8
  • 13