swiftswiftuinsnotificationcenter

How to set addObserver in SwiftUI?


How do I add NotificationCenter.default.addObserve in SwiftUI?

When I tried adding observer I get below error

Argument of '#selector' refers to instance method 'VPNDidChangeStatus' that is not exposed to Objective-C

But when I add @objc in front of func I get below error

@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes

Here is my code

let NC = NotificationCenter.default

var body: some View {
     VStack() {

     }.onAppear {

           self.NC.addObserver(self, selector: #selector(self.VPNDidChangeStatus),
                              name: .NEVPNStatusDidChange, object: nil)

     }
} 

@objc func VPNDidChangeStatus(_ notification: Notification) {
    //    print("VPNDidChangeStatus", VPNManager.shared.status)
}

Solution

  • This worked for me

       let NC = NotificationCenter.default
    
    
    
       self.NC.addObserver(forName: .NEVPNStatusDidChange, object: nil, queue: nil, 
                           using: self.VPNDidChangeStatus)
    
    
       func VPNDidChangeStatus(_ notification: Notification) {
    
    
        }