1

I need to display alert from a class which is non-UIView using objective-c.

Below is the code:

 UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@“Sample” message message:@“hello message” preferredStyle:UIAlertControllerStyleAlert];

[alertVC addAction:[UIAlertAction actionWithTitle:@"Okay" style:UIAlertActionStyleCancel handler:^(UIAlertAction * action) {}]];

[[[UIApplication sharedApplication] delegate].window.rootViewController presentViewController:alertVC animated:YES completion:nil];

this above does not work anymore and I could not any other alternative for same code in objective-c. I came across this link How to resolve: 'keyWindow' was deprecated in iOS 13.0 but solution is in Swift,not in objective-c .

Thanks

sia
  • 1,872
  • 1
  • 23
  • 54

3 Answers3

1

The problem is that in iOS 13, this expression...

[[UIApplication sharedApplication] delegate].window.rootViewController

...is nil. That's because the window property belongs to the scene delegate, not the app delegate. You would do better to access the window by way of the UIApplication itself. For example, look through the application's windows and find the one that is key.

matt
  • 515,959
  • 87
  • 875
  • 1,141
1

You are trying to present the viewcontroller in key window which will create exception. Try this code

UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Tap!" message:message preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *action = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:nil];
[alert addAction:action];
[self presentViewController:alert animated:YES completion:nil];
AJ Sanjay
  • 1,276
  • 1
  • 12
  • 29
0

I think in your case most simple would be to use the following as replacement of your last code row

[UIApplication.sharedApplication.windows.lastObject.rootViewController 
    presentViewController:alertVC animated:YES completion:nil];
Asperi
  • 228,894
  • 20
  • 464
  • 690