I have a game which displays an alert whenever a player wins. However after restarting the game and the same alert shows up multiple 'cancel' buttons show up. just like showed in the picture. any ideas what it could be,
var alertX = UIAlertController(title: "Winner", message: "X Has Won", preferredStyle:.alert)
func AlertPlayer1() {
alertX.addAction(UIAlertAction(title:"CLOSE",style: UIAlertAction.Style.destructive, handler: { (action) in self.alertX.dismiss(animated: true, completion: nil)}))
self.present(alertX, animated:true, completion:nil)
}
I have simply then just called the function whenever somebody wins
Please update your code as following to fix issue.
func AlertPlayer1() {
var alertX = UIAlertController(title: "Winner", message: "X Has Won", preferredStyle:.alert)
alertX.addAction(UIAlertAction(title:"CLOSE",style: UIAlertAction.Style.destructive, handler: { (action) in
self.alertX.dismiss(animated: true, completion: nil)
}))
self.present(alertX, animated:true, completion:nil)
}
You are creating alert instance single time, but this method AlertPlayer1 call multiple time from somewhere in your code which are adding multiple close button.
Note: As per I already told you, you method calling multiple time. So this alert also try to present multiple time, but at a time your can present only one view controller in window/screen. So it will show you warning in console.
Related
I'm new to Swift programming, but can't find an answer to my problem, which is...
When I present a simple UIAlertController with a UIAlertAction handler, I am expecting the alert to display until the user responds, then the handler is executed, before continuing with the remaining code.
Unexpectedly, it seems to finish off the code block before displaying the alert and executing the handler.
I've searched Stackoverflow, and re-read the Apple Developer Documentation for UIAlertController and UIAlertAction, but I can't figure out why the code doesn't pause until the user responds.
I've tried putting the UIAlertController code in its own function, but the alert still appears to be displaying out of sequence. I'm thinking maybe there needs to be a delay to allow the Alert to draw before the next line of code executes(?).
#IBAction func buttonTapped(_ sender: Any) {
let alert = UIAlertController(title: "Ouch", message: "You didn't have to press me so hard!", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Sorry", style: .default, handler: { _ in
self.handleAlert()
}))
self.present(alert, animated: true, completion: nil)
print("Should be printed last!")
}
func handleAlert() {
print("UIAlertAction handler printed me")
}
In the code above I am expecting the debug console to display:
UIAlertAction handler printed me
Should be printed last!
But instead it displays:
Should be printed last!
UIAlertAction handler printed me
Instead of adding a seperate function, can you put it within the alert action itself like this...
let alert = UIAlertController(title: "Ouch", message: "You didn't have to press me so hard!", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Sorry", style: .default, handler: { action in
// code for action goes here
}))
self.present(alert, animated: true)
UIAlertController is designed to run asynchronously (that is why it has you pass a block of code to execute when the action is performed instead of giving a return value)
So to fix your code, put the code you want to run after an action is chosen in another function, then call that function at the end of each UIAlertAction handler.
private var currentlyShowingAlert = false
#IBAction func buttonTapped(_ sender: Any) {
if currentlyShowingAlert {
return
}
let alert = UIAlertController(title: "Ouch", message: "You didn't have to press me so hard!", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Sorry", style: .default, handler: { _ in
self.handleAlert()
self.alertCleanup()
}))
self.present(alert, animated: true, completion: nil)
currentlyShowingAlert = true
}
func handleAlert() {
print("UIAlertAction handler printed me")
}
func alertCleanup() {
print("Should be printed last!")
currentlyShowingAlert = false
}
Be careful when doing things like pushing view controllers (or anything where the calls will stack up) in direct response to a button press.
When the main thread is busy, the button can be pressed multiple times before the first buttonTapped call happens, in that case buttonTapped could be called many times in a row, currentlyShowingAlert will prevent that issue.
I have a login screen that raises an alert when login fails. The code that calls the alert is run from a callback closure which itself calls a function in the main VC.
_ = UserProfile.logIn(emailAddressLabel.text!, passwordLabel.text!) { success in
if success {
self.performSegue(withIdentifier: "mainTabBarSegue", sender: nil)
}
else {
self.displayFailedLoginAlert()
}
self.loggingIn = false
}
and the displayFailedLoginAlert looks like this:
func displayFailedLoginAlert () {
let alert = UIAlertController(title: "Login", message: "Login Failed", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Dismiss", style: UIAlertActionStyle.default, handler: { _ in
alert.dismiss(animated: false, completion: nil)
}))
self.present(alert, animated: false, completion: nil)
}
However, when I do this I get:
Warning: Attempt to present <UIAlertController: 0x7ff8fd0b5800> on <LoginViewController: 0x7ff8fcc0deb0> which is already presenting <UIAlertController: 0x7ff8fe0cca00>
I have tried a number of different approaches and either get this or a crash if I use a UIAlertController as a class member. What am I doing wrong, I just can't see it?
You don't need to tell the alert to dismiss at all. The default behavior when tapping an action in a UIAlertController is that the alert will dismiss. Just pass nil to the handler.
The issue was that, each time the user logged in I added an observer to the API call. So, on the second login attempt the closure was called twice and so raised the error. Thanks to Frizzo for pointing me in the right direction
I have a situation where I want to present a UIAlertController in order to wait for an event (asynchronous request for data from third party) to finish before showing my main ViewController to the user to interact with.
Once the asynchronous code finishes, then I want to dismiss the UIAlertController. I know that normally UIAlertControllers are setup with a button to dismiss it, which is input from the user. I am wondering if what I want to do (dismiss with an event instead of user input) is possible?
So far, I tried to show the UIAlertController, and then wait in a while loop checking a boolean for when the event occurs:
var alert = UIAlertController(title: "Please wait", message: "Retrieving data", preferredStyle: UIAlertControllerStyle.Alert)
self.presentViewController(alert, animated: true, completion: nil)
// dataLoadingDone is the boolean to check
while (!dataLoadingDone) {
}
self.dismissViewControllerAnimated(true, completion: nil)
This gives a warning
Warning: Attempt to dismiss from view controller while a presentation or dismiss is in progress!
and does not dismiss the UIAlertController. I also tried alert.dismissViewControllerAnimated(true, completion: nil) instead of self.dismissViewControllerAnimated(true, completion: nil), but this doesn't get rid of the UIAlertController either.
I wouldn't use a while loop but a didSet observer for your dataLoadingDone property. Thereby, you may try something similar to the following code:
class ViewController: UIViewController {
var dismissAlertClosure: (() -> Void)?
var dataLoadingDone = false {
didSet {
if dataLoadingDone == true {
dismissAlertClosure?()
}
}
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
let alert = UIAlertController(title: "Please wait", message: "Retrieving data", preferredStyle: .Alert)
presentViewController(alert, animated: true, completion: nil)
// Set the dismiss closure to perform later with a reference to alert
dismissAlertClosure = {
alert.dismissViewControllerAnimated(true, completion: nil)
}
// Set boolValue to true in 5 seconds in order to simulate your asynchronous request completion
var dispatchTime: dispatch_time_t = dispatch_time(DISPATCH_TIME_NOW, Int64(5.0 * Double(NSEC_PER_SEC)))
dispatch_after(dispatchTime, dispatch_get_main_queue(), { self.dataLoadingDone = true })
}
}
Another user (matt) gave what I'm pretty sure is the correct answer, but he removed it, so I'm going to answer it. Just wanted to give credit (though he seems pretty reputable anyways).
What he wrote is that my UIAlertController presentation was not finished before I tried to dismiss it, so I got that error. I changed my code to the following:
// check if I need to wait at all
if (!dataLoadingDone) {
var alert = UIAlertController(title: "Please wait", message: "Retrieving data", preferredStyle: UIAlertControllerStyle.Alert)
self.presentViewController(alert, animated: true, completion: { () -> Void in
// moved waiting and dismissal of UIAlertController to inside completion handler
while (!self.dataLoadingDone) {
}
self.dismissViewControllerAnimated(true, completion: nil)
})
}
I moved the waiting and dismissal inside the completion handler of the presentViewController call, so that I know the presenting is done before dismissing. Also, I check if I need to wait at all with the first if statement, because otherwise another issue occurs if the while loop never does anything.
I'm not 100% sure yet, because my boolean is actually never false at the moment (the data retrieval happens really quickly). However, I have reason to believe it will take longer later on in my app development, so I will update the answer here once I have that.
EDIT: another user who previously posted an answer (Aaron Golden) was also correct about while loop blocking. I had thought that the while loop shares processing time with other events, but apparently not (or at least not enough time). Therefore, the above while loop DOES NOT work
I have a Parse Sign Up and I have an UIAlertController and I want the UIAlertController to show up with an indicator but get dismissed with another UIAlertController when there is an error in the sign up.
I have several cases for a failed sign up, all work prior to adding the UIAlertController with the indicator. And the indicator alert controller works fine when the sign up is successful and it get dismissed correctly.
//create an alert controller
let pending = UIAlertController(title: "Creating New User", message: nil, preferredStyle: .Alert)
//create an activity indicator
let indicator = UIActivityIndicatorView(frame: pending.view.bounds)
indicator.autoresizingMask = .FlexibleWidth | .FlexibleHeight
//add the activity indicator as a subview of the alert controller's view
pending.view.addSubview(indicator)
indicator.userInteractionEnabled = false // required otherwise if there buttons in the UIAlertController you will not be able to press them
indicator.startAnimating()
self.presentViewController(pending, animated: true, completion: nil)
Here is the code for the sign up, this works
if signUpError == nil {
println("Sign Up Successful")
// Keep track of the installs of our app
var installation: PFInstallation = PFInstallation.currentInstallation()
installation.addUniqueObject("Reload", forKey: "channels")
installation["user"] = PFUser.currentUser()
installation.saveInBackground()
// to stop the uialertviewcontroller once sign up successful
pending.dismissViewControllerAnimated(true, completion: {
self.performSegueWithIdentifier("goToAppFromSignUp", sender: self)
})
}
Here is where I am stuck, this is just one of the cases if I can get this to work I can do it for the others.
else {
println("Error Sign Up")
//If email has been used for another account kPFErrorUserEmailTaken
if(signUpError!.code == 203) {
let alertController = UIAlertController(title: "Sign Up Failed", message: "Sorry! Email has been taken! ", preferredStyle: .Alert)
let OKAction = UIAlertAction(title: "OK", style: .Default) { (action) in
// ...
}
alertController.addAction(OKAction)
self.presentViewController(alertController, animated: true) {
// ...
}
}
My thought was to dismiss the UIAlertController and show the next one in the completion block
pending.dismissViewControllerAnimated(true, completion: {
self.presentViewController(alertController, animated: true) {
// ...
}
})
But the app freezes on the pending alert controller (the one with the indicator). which is already presenting (null)
Any ideas? Thanks.
Try to dismiss the pending alert and present the next alert without animation.
pending.dismissViewControllerAnimated(false, completion: nil)
self.presentViewController(alertController, animated: false, completion: nil)
In the apple documentation, it states that you should not modify the view hierarchy for UIAlertController. This could cause you problems later and may be part of your current issue.
It is also likely that presenting one while the other is running is causing your issue. Dismissing the first and once complete presenting the second should in theory fix your issue. The fact it hangs suggests something else is happening. You should stop and remove the activity indicator from the view before dismissing it.
A better approach I think would be to consider using a HUD like https://github.com/jdg/MBProgressHUD to display progress or activity rather than trying to use an alert controller for a purpose it was not intended for.
A HUD is great for presenting heads up progress or activity while waiting for things to happen. It has a number of display options including activity with headline text. I would present the HUD when you are waiting and then use the alert controller to present alerts.
I have found using a HUD looks better and is much easier to control.
I have a button in a simple view with on click function :
#IBAction func watchAlert(sender: AnyObject) {
showAlert()
for i in 1...2{
AudioServicesPlaySystemSound (1005);
sleep(2)
}
}
func showAlert(){
var alert = UIAlertController(title: "Alert", message: "Message", preferredStyle: UIAlertControllerStyle.Alert)
self.presentViewController(alert, animated: true, completion: nil)
alert.addAction(UIAlertAction(title: "Ok", style: .Default, handler: dismissAlert ))
}
func dismissAlert(alertView: UIAlertAction!)
{
println("User click ok button")
}
Even though I am trying to call showAlert() before playing the audio, I could only see the alert getting displayed only after sound gets played. I want the alert to be present first and then sound should play.
Any help is appreciated.
Take out the sleep command (you must never sleep the main thread - the Watchdog process will kill you dead, and besides, you are wrongly freezing the whole interface). Instead: show the alert, then use delayed performance (as in my delay utility here) to play a sound.
(There are other problems with your code; in particular, you will also need to find a new way to play the sound twice, since you must not use sleep; this, too, can be accomplished using delay - nested.)