WWDC22 SALE: Save 50% on all my Swift books and bundles! >>

Day 84 | Project 25 | Challenge #1: Lesson learned -> never update UI outside main thread

Forums > 100 Days of Swift

Thanks to this challenge, I will never forget what Paul's been repeating for a while now: "you never manipulate user interfaces anywhere but the main thread, right? Right"

My app was crashing because I was trying to present an UIAlertViewController outside the main thread.

Hope this helps in case someone is stuck on this.

KB

1      

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.

1      

Hacking with Swift is sponsored by Emerge

SPONSORED Optimize your app’s startup time, binary size, and overall performance using Emerge’s advanced app optimization and monitoring tools. Reliably measure app size, speed up your app's startup time with Emerge's Launch Booster, and much more. Emerge is actively used by many of the top mobile development teams in the world.

Find out more

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.