Reputation: 73
NotificationCenter.default.post is not working in closures
I am having a class with the notification observers
NotificationCenter.default.addObserver(self, selector: #selector(self.methodOfReceivedNotification(notification:)), name: Notification.Name("Start"), object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(self.methodOfReceivedNotification(notification:)), name: Notification.Name("Stop"), object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(self.methodOfReceivedNotification(notification:)), name: Notification.Name("Interrupt"), object: nil)
In the same class having a method to handle the notification
@objc func methodOfReceivedNotification(notification: Notification) {
print("Notification Received")
}
When I am trying to post the observer from another class with the below code it is working fine
NotificationCenter.default.post(name: Notification.Name("Start"), object: nil)
But when trying to post the same thing inside the closure response of the network method it is not calling the methodOfReceivedNotification
Closure code
executeHttpReq(url: getUIUrl(), getparametersDict: getParameters, onSuccess: { (response, status,isEod) -> (
Any, String,Bool) in
NotificationCenter.default.post(name: Notification.Name("Start"), object: nil)
return (response,status,isEod)
}, onFailure: { (error) in
//todo send stop event to the caller
NotificationCenter.default.post(name: Notification.Name("Stop"), object: nil)
})
Is there any wrong in the code please suggest.
Upvotes: 5
Views: 4089
Reputation: 60
extension Notification.Name {
static let Start = Notification.Name("Start")
static let Stop = Notification.Name("Stop")
}
viewDidLoad
NotificationCenter.default.addObserver(self, selector: #selector(onDidReceiveData(_:)), name: .Start, object: nil)
viewController
@objc func onDidReceiveData(_ notification:Notification) {
print("image deleted by user")
// self.isExcluded = true
}
DispatchQueue.main.async {
NotificationCenter.default.post(name: .Start, object: nil)
}
Tried with my existing code.
RequestManager.shared.doPost(strURL:url, parameter: params) { (response, error) in
guard error == nil else {
return
}
do {
if let isSucess = response!["IsSuccessStatusCode"] as? Bool{
if isSucess == true{
DispatchQueue.main.async {
NotificationCenter.default.post(name: .Start, object: nil)
}
}
}
}
else{
self.showValidationAlert(message: "Try after some time")
}
}
else{
self.showValidationAlert(message: "Try after some time")
}
}
}
}
Upvotes: 1
Reputation: 1946
Try posting the notification in Main queue when it is inside closure.
DispatchQueue.main.async {
NotificationCenter.default.post(name: Notification.Name("Start"), object: nil)
}
Upvotes: 5