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)
})
代码中是否有任何错误请建议。
尝试在内部关闭时在主队列中发布通知。
DispatchQueue.main.async {
NotificationCenter.default.post(name: Notification.Name("Start"), object: nil)
}
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")
}
}
}
}