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      

Hacking with Swift is sponsored by RevenueCat

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

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.