How to programmatically dismiss UIAlertController without any buttons?
Generally the parent view controller is responsible for dismissing the modally presented view controller (your popup). In Objective-C you would do something like this in the parent view controller:
[self dismissViewControllerAnimated:YES completion:nil];
The same code in Swift versions < 3 would be:
self.dismissViewControllerAnimated(true, completion: nil)
Swift 3.0:
self.dismiss(animated: true, completion: nil)
How can I programmatically dismiss a UIAlertController
I've just been learning how to do this.
So, wherever the alert controller is built, you need to add the action button either to "OK" in default style or "Cancel" in cancel style.
UIAlertController *alertController = [UIAlertController
alertControllerWithTitle:@"You made a mistake."
message:@"Pray we don't alter the alert further"
preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *okayAction = [UIAlertAction
actionWithTitle:@"OK"
style:UIAlertActionStyleDefault
handler:^(UIAlertAction * _Nonnull action) {
[alertController dismissViewControllerAnimated:YES completion:nil];
}];
[alertController addAction:okayAction];
[self presentViewController:alertController animated:YES completion:nil];
There are other UIAlertActionStyle enumerations, such as UIAlertActionStyleCancel which will put a separator space between other actions and UIAlertActionStyleDestructive which will make the font red but will be in line with other UIAlertActions.
Make sure you add in order: standard actions (Okay, Open Camera, Photo Library) and THEN cancel actions.
There's also preferredStyle:UIAlertControllerStyleActionSheet which is used to set up options for the user. I use this to show Camera and Photo Library.
Also, for your specific dismiss action. The reason it's not working is because you are attempting to dismiss it on the background thread. You should ALWAYS dismiss or make UI changes on the foreground thread. This will cause an NSException/crash in the future.
dispatch_async(dispatch_get_main_queue(), ^{
// dismiss your UIAlertController
});
This is how you should be doing it with your specific code:
dispatch_async(dispatch_get_main_queue(), ^{
MNSHOW_NETWORK_ACTIVITY(NO);
[self refreshAnnotations:self];
[loadingAlert dismissViewControllerAnimated:YES completion:nil];
});
});
You have other issues with your code that you should ask others for help about. I am only a junior developer so I'm not sure how to correctly do what you're trying to do but this should help with dismissing.
You might want to look into loading wheels or toast messages that will say "Please wait" or "Loading".
Using a UIAlertController to show a loading message is rather bad taste.
Dismiss UIAlertController after few seconds?
May below code will do the work:
UIAlertController *alert= [UIAlertController
alertControllerWithTitle:@"Please wait, checking your PAID INVOICE, to allow the service."
message:"...waiting..."
preferredStyle:UIAlertControllerStyleAlert];
[self.window.rootViewController presentViewController:alert animated:YES
completion:nil];
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
[alert dismissViewControllerAnimated:YES completion:^{
//Dismissed
}];
});
How to dismiss UIAlertController when tap outside the UIAlertController?
Add a separate cancel action with style UIAlertActionStyleCancel
. So that when user taps outside, you would get the callback.
Obj-c
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"Alert Title" message:@"A Message" preferredStyle:UIAlertControllerStyleActionSheet];
[alertController addAction:[UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
// Called when user taps outside
}]];
Swift 5.0
let alertController = UIAlertController(title: "Alert Title", message: "A Message", preferredStyle: .actionSheet)
alertController.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: {
action in
// Called when user taps outside
}))
Dismissal of UIAlertController (best practice)
The dismissal is "included" in the presentViewController
call. You do not need a delegate because you have the completion block. In this block you put what you would normally put into the delegate callback, except the call to dismiss the alert.
As far as "best practice" is concerned, I noted that in many APIs, Apple replaced delegate callbacks with completion blocks. Apple typically recommends using the block syntax. I surmise this could be partly because it helps keeping the related code sections together.
Does UIAlertController's dismiss method without animation execute synchronously?
Like most animation methods when you dismiss the UIAlertController
you are just getting the ball rolling. The view controller is dismissed and removed asynchronously. To test this we can use some code like this:
let alert = UIAlertController(title: "Oh No!", message: ":(", preferredStyle: UIAlertControllerStyle.alert)
self.present(alert, animated: true, completion: nil)
print(presentedViewController) // Optional(<UIAlertController: 0x7fefe901e670>)
alert.dismiss(animated: true, completion: nil)
print(presentedViewController) // Optional(<UIAlertController: 0x7fefe901e670>)
As demonstrated above the alert view controller is not removed as the presented view controller right away. You can still present the new alert right after dismissing the old alert. However best practice would be to place your code for the second alert in the completion handler of the first. This completion handler is called after viewDidDisappear
is called on the presented view controller.
how to dismiss the alert programatically using swift?
I think you can use pressed(sender: UIButton!)
method in SweetAlert class.
@IBAction func aBasicMessageAlert(sender: AnyObject) {
let sweetAlert = SweetAlert().showAlert("Here's a message!")
close(sweetAlert, after: 2.0)
}
func close(alert: SweetAlert, after seconds: Double) {
NSTimer.scheduledTimerWithTimeInterval(seconds,
target: self,
selector: #selector(closeAlert),
userInfo: ["alert": alert],
repeats: true)
}
func closeAlert(timer: NSTimer) {
let alert = timer.userInfo!["alert"] as! SweetAlert
let dummyCloseButton = UIButton()
dummyCloseButton.tag = 0
alert.pressed(dummyCloseButton)
}
Why attempting to dismiss UIAlertController too early does not dismiss the Alert
Because, as long as you pass animated: true
, the alert controller will not be in the hierarchy until it is done animating, so you can't dismiss it until then. This is precisely what the completion
block is used for (generally, any good API where things happen asynchronously will provide you a completion block to let you know when that action is complete). You can dismiss immediately after presenting (though I don't imagine this is a valuable real-life use case) by doing:
present(alertController, animated: true, completion: {
alertController.dismiss(animated: true, completion: nil)
})
dismiss UIAlertController presented by a modal view controller
Don't call self dismissViewController
in the button handler. That specifically states that you want the view controller dismissed.
You don't need to dismiss the alert. It will automatically dismiss itself. The only thing you should do in the button handler is perform whatever action you need. Do nothing if you don't need to do anything.
If your alert is simply a message and you don't need to perform any action, just do this:
UIAlertAction *ok = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:nil];
Related Topics
"The Run Destination iOS Device Is Not Valid for Running the Scheme"
Uidatepicker Bug? Uicontroleventvaluechanged After Hitting Minimum Internal
Xcode 11.4. Navigation's Title Color Gone Black from Storyboard
iPad - Parsing an Extremely Huge JSON - File (Between 50 and 100 Mb)
Gem Native Extension Error While Installing Cocoapods
Orienting iOS Splash Image to Landscape/Portrait According to Launch Orientation
Move Xcode Project Causes Red Text (Missing Files from Project)
Xcode 6.3.2 Can't Run on Osx 10.11 El Capitan Developer Preview 3
iPhone Opengl Es 2.0 - Pixel Perfect Textures
Sfspeechrecognizer - Detect End of Utterance
Static Linking with Swift, Xcode6-Beta
Try Sample Avcam from Apple Found Error
How to Restrict the iOS App Only for iPhone Excluding iPad
Uilocalnotification Isn't Working at All
Automating Xcode' Debug > Simulate Location Command
Cannot Convert Value of Type Nsattributedstring.Documentattributekey to .Documentreadingoptionkey