Ferrakkem Bhuiyan
Ferrakkem Bhuiyan

Reputation: 2783

How to send a notification from UIKit to a view in SwiftUI?

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.

Upvotes: 1

Views: 1310

Answers (1)

Yrb
Yrb

Reputation: 9665

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

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

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

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

Lastly, in your SwiftUI view:

.onReceive(NotificationCenter.default.publisher(for: .didPullToRefresh)) { _ 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: .didPullToRefresh, object: value)
}

Upvotes: 7

Related Questions