NotificationCenter.default.post在闭包中不起作用
我正在和通知观察员一起上课
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)
在同一个类中具有处理通知的方法
@objc func methodOfReceivedNotification(notification: Notification) {
print("Notification Received")
}
当我尝试使用下面的代码从另一个类中发布观察者时,它工作正常
NotificationCenter.default.post(name: Notification.Name("Start"), object: nil)
但是,当尝试在网络方法的关闭响应中发布相同内容时,它并没有调用methodOfReceivedNotification
关闭代码
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)
})
代码中是否有任何错误,请提出建议。
答案 0 :(得分:0)
当通知处于关闭状态时,尝试将通知发布到主队列中。
DispatchQueue.main.async {
NotificationCenter.default.post(name: Notification.Name("Start"), object: nil)
}
答案 1 :(得分:0)
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)
}
尝试使用我现有的代码。
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")
}
}
}
}