CodexBloom - Programming Q&A Platform

Custom Notification Center not delivering notifications in iOS 17 when using SwiftUI

šŸ‘€ Views: 0 šŸ’¬ Answers: 1 šŸ“… Created: 2025-07-14
swift combine swiftui Swift

I'm updating my dependencies and I'm dealing with I'm relatively new to this, so bear with me. I've searched everywhere and can't find a clear answer... I've implemented a custom notification center that is intended to handle notifications across different views in my SwiftUI application, but I'm encountering a puzzling issue where notifications are not being delivered as expected in iOS 17. My architecture relies on Combine to publish notifications from a ViewModel and subscribe to them in various views. I have set up a simple notification system using the `PassthroughSubject` as follows: ```swift class NotificationCenter { static let shared = NotificationCenter() private var subject = PassthroughSubject<String, Never>() func post(notification: String) { subject.send(notification) } func observeNotifications() -> AnyPublisher<String, Never> { return subject.eraseToAnyPublisher() } } ``` In my ViewModel, I post notifications like this: ```swift class MyViewModel: ObservableObject { func triggerNotification() { NotificationCenter.shared.post(notification: "Data updated") } } ``` Then in my SwiftUI view, I'm trying to observe these notifications: ```swift struct ContentView: View { @StateObject private var viewModel = MyViewModel() @State private var notificationMessage: String = "" var body: some View { VStack { Text(notificationMessage) Button("Trigger Notification") { viewModel.triggerNotification() } } .onReceive(NotificationCenter.shared.observeNotifications()) { message in self.notificationMessage = message } } } ``` However, when I tap the 'Trigger Notification' button, the `notificationMessage` is not updating; it remains empty. I've verified that the `triggerNotification` function is indeed called, but I suspect there may be an issue with how the subscribers are being managed in SwiftUI. I've also checked that `NotificationCenter.shared.observeNotifications()` returns an active publisher. The problem persists even after trying to use `DispatchQueue.main.async` to ensure UI updates. Has anyone experienced similar issues or can provide insights on how to properly implement a notification system in SwiftUI for iOS 17? I’m particularly concerned about any changes in Combine behavior between iOS versions that might affect this implementation. My development environment is Linux. Any help would be greatly appreciated! I'm working on a service that needs to handle this. For context: I'm using Swift on Linux. Thanks in advance! I've been using Swift for about a year now. Thanks for any help you can provide! I appreciate any insights!