Instance Method インスタンスメソッド

notifications(named:object:)

Returns an asynchronous sequence of notifications produced by this center for a given notification name and optional source object.

Declaration 宣言

func notifications(named name: Notification.Name, object: AnyObject? = nil) -> NotificationCenter.Notifications

Parameters パラメータ

name

A notfiication 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.

The following iOS example iterates over an asynchronous sequence of orientationDidChangeNotification notifications. It uses the AsyncSequence method filter(_:) to only receive notifications when the device rotates into the upright portrait orientation.


UIDevice.current.beginGeneratingDeviceOrientationNotifications()
for await notification in NotificationCenter.default.notifications(
        named: UIDevice.orientationDidChangeNotification)
        .filter({ _ in
            return UIDevice.current.orientation == .portrait
        })
{
    print("Device is now in portrait orientation.")
}

See Also 参照

Receiving Notifications as an Asynchronous Sequence