简体   繁体   中英

Alert does not appear immediately iOS

I created an alert within a method that is invoked when the parser goes wrong.

The alert works properly, but appears after about 10 seconds. As you can see below in the method I put a println () which appears immediately and after about 10 seconds to display the alert.

My code:

func XMLParserError(parser: ParserData, error: String) {
    println(error)
    print("Error parser")
    let alert = UIAlertView()
    alert.title = "Error"
    alert.message = "Parser error."
    alert.addButtonWithTitle("OK")
    alert.show()
}

As far as I know all UI related event needs to be on main thread. Here It looks like XMLParserError function create delays to execute some processing.

So you need to show alert on main thread in this method. Use dispatch_async

dispatch_async(dispatch_get_main_queue(),{
       alert.show()
});

Edit: More explanation:

UI events are fast and responsive. So that user can get rich experience in application. So lengthy tasks or events which requires network access or some complex computation are needs to be in background and therefor if you like to write a code in kind of this situation you must have to call UI events in main threads.

Make sure you are presenting the UIAlertView in the main thread.

   dispatch_async(dispatch_get_main_queue(), {
      let alert = UIAlertView()
      alert.title = "Error"
      alert.message = "Parser error."
      alert.addButtonWithTitle("OK")
      alert.show()
   }

All UI activity should always be executed on the main thread, if you do not you can't be sure when it will be executed. Which will cause the behavior you explained in your question.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM