Reputation: 2352
I have been using UIAlertController
in previous apps but I am facing a strange error this time. Here is my code which I using to present it:
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:ALERT_TITLE_STRING message:message preferredStyle:UIAlertControllerStyleAlert];
[alertController addAction:[UIAlertAction actionWithTitle:OK_STRING style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
}]];
[[[[UIApplication sharedApplication] keyWindow] rootViewController] presentViewController:alertController animated:YES completion:^{
}];
Everything was fine but now I my app crashes on last line. Here is error:
This application is modifying the autolayout engine from a background thread, which can lead to engine corruption and weird crashes. This will cause an exception in a future release.
I am not using autolayout
in my app. I have no idea why I am getting this error.
Any clues?
Upvotes: 3
Views: 3402
Reputation: 6038
You can't handle UI in any other thread than the main thread.
If you're currently in another thread, you can force a block of code to be executed on the main thread anyway, by putting it inside the following block.
dispatch_async(dispatch_get_main_queue(), ^{
//Display your UIAlertController here
});
Upvotes: 6
Reputation: 2521
This error is displayed when you try to do UI tasks in a background thread. Just change your code to this:
dispatch_async(dispatch_get_main_queue(), ^{
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:ALERT_TITLE_STRING message:message preferredStyle:UIAlertControllerStyleAlert];
[alertController addAction:[UIAlertAction actionWithTitle:OK_STRING style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
}]];
[[[[UIApplication sharedApplication] keyWindow] rootViewController] presentViewController:alertController animated:YES completion:^{
}];
});
Upvotes: 9
Reputation: 119272
You're not allowed to perform UI operations on any thread but the main thread. The alert controller will be using autolayout internally which is why you're seeing the error.
Use dispatch_async
to present the alert from the main thread instead.
Upvotes: 2