0

I am creating a signup screen and using firebase sdk on backend . i have add some if Conditions in my signup form and when ever if a textfield is left empty in form and register button is pressed i am showing a UIAlertView with a Title,Message and ok Button . but i am seeing a Thread exception while running app which says

Application tried to present modal view controller on itself. Presenting controller is < UIAlertController: 0x7fb750849200>.

and show stack and at the end of error stack it says

libc++abi.dylib: terminating with uncaught exception of type NSException

code for my alertfunction is

func ShowAlert(Title:String,Message:String){

    let alert = UIAlertController(title: Title, message: Message, preferredStyle: UIAlertControllerStyle.alert)
    alert.addAction(UIAlertAction(title:"OK", style: UIAlertActionStyle.default, handler: { (action) in
        alert.dismiss(animated: true)
    }))

    alert.present(alert,animated: true)
}

i am feeling is that its some main thread issue but i don't know how to resolve.

James Z
  • 12,209
  • 10
  • 24
  • 44
Muhammad Usman
  • 795
  • 7
  • 19

1 Answers1

2

The current view controller should present the alert so just …

present(alert,animated: true)

rather than

alert.present(alert,animated: true)

Update

From your comment, it sounds like you're trying to present the alert on a background thread. In addition to the above, you should always present alerts (or perform any UI action) on the main thread…

DispatchQueue.main.async {
    showAlert(title: "My title", message: "My Message")
}

Side note

All variables, parameters and func names in Swift should begin with a lower case letter, e.e.g

func showAlert(title: String, message: String)

instead of

func ShowAlert(Title:String,Message:String)
Ashley Mills
  • 50,474
  • 16
  • 129
  • 160
  • it doest display the alert box if i replace alert.present(alert,animated: true) with present(alert,animated: true) – Muhammad Usman Aug 05 '18 at 12:27
  • 2
    `func showAlert(title:String, message:String)` => `func showAlert(title: String, message: String)` with space after ":" should be even better. – Larme Aug 05 '18 at 12:44
  • I used DispatchQueue.main.async { showAlert(title: "My title", message: "My Message") } but now its showing a different error : 'Application tried to present modal view controller on itself. Presenting controller is . – Muhammad Usman Aug 05 '18 at 19:39
  • Please read my full answer. You need to do both things. Present from self, _and_ on the main queue – Ashley Mills Aug 05 '18 at 19:41
  • great , it worked . actually it was self.present(alert,animated: true) – Muhammad Usman Aug 05 '18 at 20:13
  • actually i am new to IOS thats why doing silly things . besides , Thanks again Brother – Muhammad Usman Aug 05 '18 at 20:14