如何在单例中获取UIViewController?

时间:2017-07-17 09:41:55

标签: ios swift

我使用单例类来验证网络响应。在函数(validResponse())内部,我调用单例,我调用另一个弹出警告框的函数,让用户知道有错误。

我的单件类中的函数:

func validResponse(data: Data?, response: URLResponse?, error: Error?, viewController: UIViewController, context: String?) -> Bool {
    ...
    DispatchQueue.main.async {
            AlertHelper.showAlertWrapper(viewController: viewController, alertTitle: "Error", alertMessage: self.genericError)
        }
}

AlertHelper代码:

class AlertHelper {
    static func showAlertWrapper(viewController: UIViewController, alertTitle: String, alertMessage: String) {
        let alertController = UIAlertController(title: alertTitle, message: alertMessage, preferredStyle: .alert);

        let okAction = UIAlertAction(title: "OK", style: .default, handler: nil);
        alertController.addAction(okAction);

        viewController.present(alertController, animated: true, completion: nil);
    }
}

致电validResponse()

let result = self.networkHelper.validResponse(data: data, response: response, error: error, viewController: self, context: "Delete section")

在上面的例子中,self不会起作用,只是暂时在那里,直到我弄清楚要做什么。我理解我可以在UIViewController中传递相关的viewController,就像我为showAlertWrapper所做的那样。然而,这有点凌乱。

有没有什么方法可以在我的单例类中引用当前存在的视图控制器,这样我就不必在validResponse()中传递它?

2 个答案:

答案 0 :(得分:1)

一种解决方法,也许更快捷的方法是在UIViewController中使用showAlertWrapper

extension UIViewController {
func showAlertWrapper(title: String, message: String) {
        let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert);

        let okAction = UIAlertAction(title: "OK", style: .default, handler: nil);
        alertController.addAction(okAction);

       present(alertController, animated: true, completion: nil);
    }
}

然后你会做

DispatchQueue.main.async {
            viewController.showAlertWrapper(title: "Error", message: self.genericError)
        }

答案 1 :(得分:1)

您可能希望获得当前在您的应用中显示的最顶级视图控制器。您可以通过在单身人士想要显示错误时检索最顶层的视图控制器来执行此操作。

class AlertHelper {
    static func showAlertWrapper(alertTitle: String, alertMessage: String) {
        let alertController = UIAlertController(title: alertTitle, message: alertMessage, preferredStyle: .alert);

        let okAction = UIAlertAction(title: "OK", style: .default, handler: nil);
        alertController.addAction(okAction);

        if var topController = UIApplication.sharedApplication().keyWindow?.rootViewController {
            while let presentedViewController = topController.presentedViewController {
                topController = presentedViewController
            }

            // viewController should now be your topmost view controller
            viewController.present(alertController, animated: true, completion: nil);
        }
    }
}

并调用showAlertWrapper:

AlertHelper.showAlertWrapper(alertTitle: "Error", alertMessage: self.genericError)