#swift #swiftui #nsnotificationcenter
#swift #swiftui #nsnotificationcenter
Вопрос:
У меня есть следующий код, в котором я создаю класс, который действует как наблюдатель уведомления по умолчанию. Но уведомление никогда не приходит:
struct NotificationCenterExampleView: View {
let observerA = ObserverClassA()
init() {
print("NotificationCenterExampleView init")
NotificationCenter.default.addObserver(observerA, selector: #selector(ObserverClassA.receivedNotification(notification:)), name: Notification.Name("CustomNotification"), object: "This is the message")
let notificationToPost = Notification(name: Notification.Name("CustomNotification"), object: "Message being sent", userInfo: nil)
NotificationCenter.default.post(notificationToPost)
}
var body: some View {
Text("Notification Center Example")
.frame(minWidth: 250, maxWidth: 500, minHeight: 250, maxHeight: 500)
}
}
class ObserverClassA: NSObject {
@objc func receivedNotification(notification: Notification) {
let message = notification.object as! String
print("Message received: (message)")
}
}
Я знаю, что использование .publisher
и onReceive
это будет работать внутри структуры представления, но какова фактическая причина, по которой этот код не работает?
Ответ №1:
Уведомления, соответствующие объекту, поэтому, если вы подписываетесь на один объект, но публикуете с другим объектом, подписчик не запускается.
Вот исправленный вариант. Протестировано с помощью Xcode 12.1.
NotificationCenter.default.addObserver(observerA,
selector: #selector(ObserverClassA.receivedNotification(notification:)),
name: Notification.Name("CustomNotification"),
object: nil) // << subscribe for all
let notificationToPost = Notification(name: Notification.Name("CustomNotification"), object: "This is the message", userInfo: nil)
NotificationCenter.default.post(notificationToPost)