lithium lithium - 1 month ago 23
Swift Question

Strange delay with alert in UITableView

I have some

UITableView
with data from internal
array
. I want to show
UIAlertController
on tap but I'm experiencing very strange delay.

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

print("tapped \(dispatcher.conversations[indexPath.row].name)") //this one works fine, no problems here

let message = dispatcher.conversations[indexPath.row].desc + "\n\nDo you wanna play this?"
let alertname = dispatcher.conversations[indexPath.row].name

let alert = UIAlertController(title: alertname, message: message, preferredStyle: .alert)

let actionOK = UIAlertAction(title: "Play", style: UIAlertActionStyle.default, handler: { (action) in
//play the file
})

let actionCancel = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.cancel, handler: { (action) in
//cancel the file
})

alert.addAction(actionOK)
alert.addAction(actionCancel)

self.present(alert, animated: true, completion: {
//some code here
})


My first alert has some delay, but it is mostly ok. But if I'm trying to tap the next cell, I have to wait several seconds for my alert to show.

So, it seems I don't have any problems with access to my data (print works just fine), but somehow it needed several seconds to show UIAlertController after that.

What did I do wrong?

Answer

Present it on your main queue instead:

DispatchQueue.main.async(execute: {
    self.present(alert, animated: true, completion: {
    //some code here
    })
})