UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

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

3      

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.

3      

TAKE YOUR SKILLS TO THE NEXT LEVEL If you like Hacking with Swift, you'll love Hacking with Swift+ – it's my premium service where you can learn advanced Swift and SwiftUI, functional programming, algorithms, and more. Plus it comes with stacks of benefits, including monthly live streams, downloadable projects, a 20% discount on all books, and free gifts!

Find out more

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

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

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.