I am updating some UIAlertViews, deprecated since iOS 9.0 to UIAlertViewControllers.
With UIAlertView, it was possible to just throw an alert from any code being executed--even in a utility class or shared instance--with the simple line:
[alertView show];
So if I call a shared instance such as
- (void)didTapDeleteButton:(id)sender {
NSArray *itemsToDelete = [self.selectedIndexPathToContact allValues];
[[IDModel sharedInstance] deleteItems:itemsToDelete];
//which contains the code:
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Keep Archive Copy?"
message:nil
delegate:self
cancelButtonTitle:@"No"
otherButtonTitles:@"OK",nil];
alertInvite.alertViewStyle = UIAlertViewStyleDefault;
alertInvite.tag=100;
[alertView show];
everything worked fine.
However, with the UIAlertController, this is not allowed. If you put the following code in the method of a class accessible via shared instance, when you get to presentViewController, it throws an error:
UIAlertController *alertView = [UIAlertController alertControllerWithTitle:@"Delete Item?" message:nil preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction* yesButton = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) {
[alertView dismissViewControllerAnimated:YES completion:nil];
}];
UIAlertAction* noButton = [UIAlertAction actionWithTitle:@"Not Now" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) {
[alertView dismissViewControllerAnimated:YES completion:nil];
}];
[alertView addAction:noButton];
[alertView addAction:yesButton];
if ([alertView respondsToSelector:@selector(setPreferredAction:)]) {
[alertView setPreferredAction:yesButton];
}
//FOLLOWING THROWS ERROR
[self presentViewController:alertView animated:YES completion:nil];
on the last line, that the class (reached via a shared instance) does not have this method. It seems you must use a more complicated way to throw alert. I've seen some somwehat convoluted approaches such as the following:
id rootViewController = [UIApplication sharedApplication].delegate.window.rootViewController;
if([rootViewController isKindOfClass:[UINavigationController class]])
{
rootViewController = ((UINavigationController *)rootViewController).viewControllers.firstObject;
}
if([rootViewController isKindOfClass:[UITabBarController class]])
{
rootViewController = ((UITabBarController *)rootViewController).selectedViewController;
}
[rootViewController presentViewController:alertInvite animated:YES completion:nil];
However, this does not work for me as I don't think my shared instance has a rootviewcontroller. Can anyone suggest a simple, straightforward way to do this?