Search code examples
iosswiftdispatch-queue

Swift threading multiple tasks?


I have this label that is supposed to display a username. Now, I have done quite a bit of IOS developing, however threading is still a bit unclear to me. How would I make sure this code finishes:

User(name: "", email: "", _id: "").getCurrentUser(userId: userId)

Before this gets excecuted?:

self.nameLabel.text = currentUser.name

I have been fumbling with DispatchQueue but I can't seem to figure it out... Thx in advance!


Solution

  • Just send a notification in your getCurrentUser() method and add an observer in your UIViewController to update the label.

    public extension Notification.Name {
        static let userLoaded = Notification.Name("NameSpace.userLoaded")
    }
    
    let notification = Notification(name: .userLoaded, object: user, userInfo: nil)
    NotificationCenter.default.post(notification)
    

    And in your UIViewController:

    NotificationCenter.default.addObserver(
            self,
            selector: #selector(self.showUser(_:)),
            name: .userLoaded,
            object: nil)
    
    func showUser(_ notification: NSNotification) {
        guard let user = notification.object as? User,
            notification.name == .userLoaded else {
                return
        }
        currentUser = user
        DispatchQueue.main.async {
            self.nameLabel.text = self.currentUser.name
        }
    }