Automatically run UIAlertAction by UIAlertController software
I want my UIAlertController to click the Cancel button when my application goes to the background.
I have set a background notification with
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appDidEnterBackground) name:UIApplicationDidEnterBackgroundNotification object:nil];
Then, in my appDidEnterBackground function, I have:
- (void)appDidEnterBackground {
if (_alertController) {
UIAlertAction *cancelAction = [[_alertController actions] objectAtIndex:0];
//HERE: is there a way to trigger the cancelAction??
[_alertController dismissViewControllerAnimated:NO completion:nil];
}
}
What I am struggling with is how to programmatically trigger the UIAlertAction. Is it possible?
+3
source to share
1 answer
I answered this with a suggestion made by MCKapur.
I already had a UIAlertController in singleton mode. What I did was define a variable in my singlelet to keep the completion action:
@property (copy, nonatomic) void (^completion)(BOOL);
Then when I configured the UIAlertController to show it, I also set the completion code with:
_completion = ^(BOOL cancelled) {
if (block) {
block (NO, nil);
}
};
Finally, I changed the call to appDidEnterBackground to:
- (void)appDidEnterBackground {
if (_alertController) {
if (_completion) {
_completion(NO);
_completion = nil;
}
[_alertController dismissViewControllerAnimated:NO completion:nil];
}
}
+4
source to share