我在应用程序启动后显示警告时出现问题。我正在使用通知中心观察通知错误并找到当前可见的视图控制器以显示警报。当我在启动应用程序后处理错误时,这项工作,但如果我想在启动应用程序后显示此错误,则不会发生。 我的app delegate代码:
func listenForRealmErrorNotification() {
NotificationCenter.default.addObserver(forName: MyDataModelDidFailNotification, object: nil, queue: OperationQueue.main, using: { notification in
let alert = UIAlertController(title: NSLocalizedString("Internal alert", comment: "Internal error header"),
message: NSLocalizedString("There was an error while working whith your data", comment: "Internal error description") + "\n\n" + NSLocalizedString("Press OK to terminate the app. Sorry for the inconvenience", comment: "Internal error excuses"),
preferredStyle: .alert)
let action = UIAlertAction(title: NSLocalizedString("OK", comment: "Agree button on internal error"), style: .default, handler: {_ in
let exeption = NSException(name: NSExceptionName.internalInconsistencyException, reason: "Realm error", userInfo: nil)
exeption.raise()
})
alert.addAction(action)
print("***Observe error")
self.viewControllerForShowingAlert().present(alert, animated: true, completion: nil)
})
}
func viewControllerForShowingAlert() -> UIViewController {
let rootViewController = self.window!.rootViewController!
return topViewController(from: rootViewController)
}
func topViewController(from controller: UIViewController) -> UIViewController {
if controller is UINavigationController {
return topViewController(from: (controller as! UINavigationController).visibleViewController!)
}
if controller is UITabBarController {
return topViewController(from:(controller as! UITabBarController).selectedViewController!)
}
if let presentedViewController = controller.presentedViewController {
return topViewController(from:presentedViewController)
}
return controller
}
发布通知的代码:
func fatalRealmError(_ error: Error) {
print("***Fatal error with dataBase: \(error)")
Crashlytics.sharedInstance().recordError(error)
NotificationCenter.default.post(name: MyDataModelDidFailNotification, object: nil)
}
更新: 在委托中启动我的数据源:
func initialDataSource() {
do {
dataSource = try UserDataSource()
}
catch let error as NSError {
fatalRealmError(error)
}
}
在这里,我设置了观察员:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
customizeAppearance()
listenForRealmErrorNotification()
initialDataSource()
let rootViewController = window?.rootViewController as! UINavigationController
let rootContentController = rootViewController.viewControllers[0] as! YourFoodViewController
rootContentController.dataSource = dataSource
Fabric.with([Crashlytics.self])
return true
}