Home > Back-end >  How to send a notification from UIKit to a view in SwiftUI?
How to send a notification from UIKit to a view in SwiftUI?

Time:03-17

I am trying to send a notification from UIViewcontroller to SwiftUI View after the user did pull to refresh.

 @objc private func fetchScheduleData(_ sender: UIRefreshControl) {
        NotificationCenter.default.post(name: Notification.Name(rawValue: "didPullToRefreash"), object: nil)
     
    }

On SwiftUI view i trying to set this method .onchange()

   NotificationCenter.default.addObserver(self, selector: #selector(didPullToRefreashHelper), name: Notification.Name(rawValue: "didTapNotification"), object: nil)

But onChange it's not working. I am wondering i how i will do this.

CodePudding user response:

The simplest way of doing this would be to first, create the custom notification like this:

extension Notification.Name {
    static let didPullToRefreash = Notification.Name("didPullToRefreash")
}

That now lets you address it with dot notation. Next, in your VC:

 @objc private func fetchScheduleData(_ sender: UIRefreshControl) {
        NotificationCenter.default.post(name: .didPullToRefreash, object: nil)
    }

Lastly, in your SwiftUI view:

.onReceive(NotificationCenter.default.publisher(for: .didPullToRefreash)) { _ in
    // If you are passing an object, this can be "notification in"

    // Do something here as a result of the notification
}

edit:

If you want to send a message in a SwiftUI view when a variable changed, then you could use .onChange(of:) like this:

.onChange(of: watchedStateVar) { value in
    NotificationCenter.default.post(name: .didPullToRefreash, object: value)
}
  • Related