notifications(named:object:)
Returns an asynchronous sequence of notifications produced by this center for a given notification name and optional source object.
Declaration
@preconcurrency func notifications(named name: Notification.Name, object: (any AnyObject & Sendable)? = nil) -> NotificationCenter.NotificationsParameters
- name:
A notification name. The sequence includes only notifications with this name.
- object:
A source object of notifications. Specify a sender object to deliver only notifications from that sender. When
nil, the notification center doesn’t consider the sender as a criteria for delivery.
Return Value
An asynchronous sequence of notifications from the center.
Discussion
Use this method to receive notifications from the center as an AsyncSequence. You iterate over this sequence with for-await-in syntax.
Notification doesn’t conform to Sendable, because several of its members can’t be sendable, such as object and the userInfo dictionary. If you iterate over the notifications in this sequence, Xcode issues a warning about crossing an actor boundary. To handle this, use a NotificationCenter/Notifications/map(_:)-3wc5j or NotificationCenter/Notifications/compactMap(_:)-6wlbd to extract sendable properties of the notification, such as its name or sendable values from the userInfo dictionary.
The following macOS example calls notifications(named:object:) to receive an asynchronous sequence of didActivateApplicationNotification notifications from the shared NSWorkspace notification center. It then uses a NotificationCenter/Notifications/compactMap(_:)-6wlbd to retrieve NSRunningApplication values from the notification’s userInfo dictionary, from which it gets localizedName strings. Since the String type conforms to Sendable, you can iterate over this type without a compiler warning.
for await appName in NSWorkspace.shared.notificationCenter.notifications (
named: NSWorkspace.didActivateApplicationNotification)
.compactMap ({ notification in
guard let appInfo = notification.userInfo?[NSWorkspace.applicationUserInfoKey] as? NSRunningApplication,
let name = appInfo.localizedName else { return nil as String? }
return name
})
{
print("Application activated: \(appName)")
}