ios – NotificationCenter.default.notifications not returning all notifications


In a SwiftUI app, I am posting notifications from the main thread, and receiving notifications in async Task:

Post:

.onAppear { 
    NotificationCenter.default.post(name: Self.notifName, 
                                    object: nil, 
                                    userInfo: ["userId": userId])
}

Receive in a Task:

    for await userId in NotificationCenter.default.notifications(named: Self.notifName)
       .compactMap ({ notification in
            guard let userId = notification.userInfo?["userId"] as? String else {
                return nil as String?
            }
                return userId
            }) {
               // do work
            }

The problem is: for some reason, the for await loop only receives 8 notifications while there are 18 notifications posted.

Is this because the for await probably runs in another thread other than the main thread? If that’s the problem, why did it still receive some of the notifications?

XCode: 14.2

iOS: 16

EDIT:

Updated the “POST” part of the code to show it is in the UI thread. I will try to come up with a mini sample that can reproduce the issue.

EDIT2:

The notifications we did receive is the 1st notification and the last 7 notifications. What missed is the 10 notifications in between.

Latest articles

spot_imgspot_img

Related articles

Leave a reply

Please enter your comment!
Please enter your name here

spot_imgspot_img