Replace UIAlertController with another UIAlertController - ios

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.

Related

Swift - How to stop the keyboard from dismissing when an alert shows up

I have a simple view with a text field that becomes the first responder when the view loads. If the user enters the wrong code, an 'oops' alert dialogue pops up, and the keyboard dismisses, and upon clicking an option on the alert dialogue, the keyboard appears again, resulting in my view moving about.
Is there a way to stop this keyboard - ever - dismissing? I tried to use this I found elsewhere:
override var disablesAutomaticKeyboardDismissal: Bool { return true }
however it doesn't seem to fix the problem. Could anyone give me a heads up? :) Thanks!
fixed with the following solution, modified from this answer - https://stackoverflow.com/a/47068284/14815664
func displayError(message: String) {
let controller = UIAlertController(title: "Oops!", message: message, preferredStyle: .alert)
controller.addAction(UIAlertAction(title: "Dismiss", style: .default))
guard let alertWindow = UIApplication.shared.windows.last,
alertWindow.windowLevel == UIWindow.Level(rawValue: 10000001.0) else {
navigationController.present(controller, animated: true, completion: nil)
return
}
alertWindow.rootViewController?.present(controller, animated: true, completion: nil)
}

same alert shows up multiple 'cancel' buttons

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.

Unable to dismiss a UIAlertController called from a closure

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

Why is my app resetting due to a function that has nothing to do with resetting it?

I am writing a swift/Xcode app and have a particular page where a user can upload a picture, which is saved to a database. Upon success of the upload, I give the user a pop up telling them that the save was successful. Here is the relevant code for that bit:
func displayAlert(title: String, message: String){ //all possible alerts go into here
if #available(iOS 8.0, *) {
let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "Ok", style: .Default, handler: { (action) in
self.dismissViewControllerAnimated(true, completion: nil)
}))
self.presentViewController(alert, animated: true, completion: nil)
} else {
// Fallback on earlier versions
}
}
Thats the function that is called. Here is where and how it is called:
if error == nil{
self.imageToPost.image = UIImage(named: "blah.jpg" )
self.message.text = "" //input fields are set back to original
self.displayAlert("Success", message: "Your image has been uploaded")
} else{}
If the image is uploaded successfully, which it is, the error returns nil and the code runs. The user gets the alert, clicks ok, and then... the app resets. It doesn't close out, but immediately goes to the main page viewcontroller (which is not this page's viewcontroller)
I have deduced that the displayAlert function must be at fault, because commenting out the self.displayAlert("Success", .....) fixes the issue, and the app does not reset. But I see nothing in the syntax that would cause this issue. (There is the exact same function in the main page's swift file - I copied and pasted it over - could that be the issue?). I am stumped
Your call to self.dismissViewControllerAnimated(true, completion: nil) dismisses your view and shows your previous ViewController (Main) in the stack.

iOS dismiss UIAlertController in response to event

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

Resources