Swift 4 - Notification Center addObserver issue
Data Receiving - Add observer:
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector: #selector(yourfunction(notfication:)), name: .postNotifi, object: nil)
}
@objc func yourfunction(notfication: NSNotification) {
print("xxx")
}
Sending Data - Post Notification:
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
NotificationCenter.default.removeObserver(self, name: .postNotifi, object: nil)
}
extension Notification.Name {
static let postNotifi = Notification.Name("postNotifi")
}
You can improve your code with these steps:
extension Notification.Name {
static let dataDownloadCompleted = Notification.Name(
rawValue: "dataDownloadCompleted")
}
And use it like this:
let notificationCenter = NotificationCenter.default
notificationCenter.addObserver(self,
selector: #selector(YourClass.sayHello),
name: .dataDownloadCompleted,
object: nil)
But as was already pointed out, issue is solved by changing to #selector