How to use notificationcenter in swiftui with example

Feb 05, 2022 iOS

How to use notificationcenter in swiftui with example

Notifications on iOS are a simple and effective method to communicate data in a loosely linked manner. That is, the sender of a notification doesn’t have to worry who (if anybody) receives the message; it just broadcasts it to the rest of the app, where it may be picked up by a variety of things or nothing at all depending on the state of your app.

As an example, you could want different portions of your app to perform something when a user signs in – for example, you might want certain views to refresh, a database to update itself, and so on. Simply post a notice with the following name:

let notify = NotificationCenter.default
notify.post(name: Notification.Name("Userinfo"), object: nil)

We can add the observer in the other content view to get notified in SwiftUI

notify.addObserver(self, selector: #selector(Userinfo), name: Notification.Name("Userinfo"), object: nil)

Notifications from NotificationCenter are used by a vast variety of frameworks and user interface components to convey information about their state and interactions. In Apple’s instructions, there’s a section on receiving and managing events with Combine that expressly mentions NotificationCenter.

Notifications sent using NotificationCenter give a centralised destination for occurrences inside your application.

You may also add your own alerts to your app, and when you send them, you can include an extra dictionary in their userInfo parameter. An example of customizing a notice. myExampleNotification:

Example for NotificationCenter in SwiftUI

extension NSNotification {
    static let UserData = Notification.Name.init("UserLogs")
}

First View

struct FirstView: View {
    var body: some View {
        HStack {
            SecondView()
        }
        .onReceive(NotificationCenter.default.publisher(for: NSNotification.UserData))
        { data in
           // Change key as per your "UserLogs"
            guard let userInfo = data.userInfo, let info = userInfo["UserInfo"] else {
                    return 
           }
        }
    }
}

Second View

struct SecondView: View {
    var body: some View {
             Text("Hello World")
            .frame(width: 20,height: 30, alignment: .center)
            .foregroundColor(.red)
            .onTapGesture {
                NotificationCenter.default.post(name: NSNotification.UserData, 
                                                object: nil, userInfo: ["Userinfo": "Test"])
        }
    }
}

In SwiftUI, you can use the NotificationCenter to send and receive notifications between different parts of your application. Here’s an example of how to use NotificationCenter in SwiftUI:

First, define the notification name as a constant:

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

Next, in the sender view, post a notification:

Button("Send Notification") {
    NotificationCenter.default.post(name: .didReceiveData, object: nil)
}

In the receiver view, add an observer to listen for the notification:

.onAppear {
    NotificationCenter.default.addObserver(forName: .didReceiveData, object: nil, queue: nil) { _ in
        // Handle the notification
    }
}

Be sure to remove the observer in the onDisappear modifier to prevent memory leaks:

.onDisappear {
    NotificationCenter.default.removeObserver(self)
}

That’s it! Now when the user taps the “Send Notification” button in the sender view, the receiver view will receive the didReceiveData notification and execute the code in the closure.