Alek Piasecki Alek Piasecki - 4 months ago 7
Swift Question

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

Answer

Your call to self.dismissViewControllerAnimated(true, completion: nil) dismisses your view and shows your previous ViewController (Main) in the stack.