Latest Post

How to use closure button in swift How to use notificationcenter in swiftui with example Longest common subsequence program in swift

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"])
        }
    }
}

Leave a Reply

Your email address will not be published.