Yes. Running code on the background thread should be reserved for time consuming tasks like decoding or maintenance 😊
By the way to prevent this issue in your future projects, or have a peace of mind with reusable code, consider having an extension on UIViewController
, something like this
// UIViewController+Ext.swift
import UIKit
extension UIViewController {
func presentAlertOnMainThread(title: String, message: String, buttonTitle: String, otherActions: [UIAlertAction]? = nil) {
DispatchQueue.main.async {
let alertVC = UIAlertController(title: title, message: message, preferredStyle: .alert)
let defaultAction = UIAlertAction(title: buttonTitle, style: .default)
alertVC.addAction(defaultAction)
if otherActions != nil { otherActions?.forEach { alertVC.addActions($0) } }
self.present(alertVC, animated: true)
}
}
}
Apart from the defaultAction
e.g. an "OK" button, for the otherActions
parameter, we could declare any other UIAlertAction
we desire then pass it to this function above as an array.