Skip to content

Instantly share code, notes, and snippets.

@mxcl
Last active July 5, 2018 18:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mxcl/36de8f6f13e53872f11248d7ff2b1abc to your computer and use it in GitHub Desktop.
Save mxcl/36de8f6f13e53872f11248d7ff2b1abc to your computer and use it in GitHub Desktop.
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