Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
import PromiseKit
public extension UIViewController {
@discardableResult
func alert(error: Error, title: String? = nil, file: StaticString = #file, line: UInt = #line) -> Guarantee<Void> {
let (promise, seal) = Guarantee<UIAlertAction>.pending()
let alert = UIAlertController(title: title ?? String(describing: type(of: error)), message: error.legibleDescription, preferredStyle: .alert)
alert.addAction(.init(title: "OK", style: .default, handler: seal))
if let transitionCoordinator = transitionCoordinator {
let window = self.view.window
transitionCoordinator.animate(alongsideTransition: nil, completion: { [weak self] _ in
if let presenter = self ?? window?.rootViewController {
presenter.present(alert, animated: true)
}
})
} else if let vc = UIApplication.shared.visibleViewController, vc.view != nil {
vc.present(alert, animated: true)
} else if view.window != nil {
present(alert, animated: true)
} else {
print("error: Could not present UIAlertViewController")
return Guarantee()
}
print("\(file):\(line)", error) // you should log some of these to Sentry
return promise.asVoid()
}
}
extension UIApplication {
var visibleViewController: UIViewController? {
var vc = UIApplication.shared.keyWindow?.rootViewController
while let presentedVc = vc?.presentedViewController {
if let navVc = (presentedVc as? UINavigationController)?.viewControllers.last {
vc = navVc
} else if let tabVc = (presentedVc as? UITabBarController)?.selectedViewController {
vc = tabVc
} else {
vc = presentedVc
}
}
return vc
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.