-
Notifications
You must be signed in to change notification settings - Fork 32
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #41 from sanzaru/notification-center-publisher
Notification center publisher
- Loading branch information
Showing
2 changed files
with
134 additions
and
9 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
32 changes: 32 additions & 0 deletions
32
Sources/SimpleToast/SimpleToastNotificationPublisher.swift
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,32 @@ | ||
// | ||
// SimpleToastNotificationPublisher.swift | ||
// SimpleToast | ||
// | ||
// This file is part of the SimpleToast Swift library: https://github.com/sanzaru/SimpleToast | ||
// Created by Martin Albrecht on 25.09.24. | ||
// Licensed under Apache License v2.0 | ||
// | ||
|
||
import SwiftUI | ||
|
||
public struct SimpleToastNotificationPublisher { | ||
public static func publish<ToastNotification: Identifiable>(notification: ToastNotification) { | ||
NotificationCenter.default.post(name: .toastNotification, object: notification) | ||
} | ||
} | ||
|
||
private extension Notification.Name { | ||
/// Name for published `NotificationCenter.Publisher` notifications | ||
static let toastNotification = Notification.Name("SimpleToastNotification") | ||
} | ||
|
||
public extension View { | ||
/// Handle NotificationCenter events for SimpleToast | ||
/// - Parameter action: The action to perform when a notification is received | ||
/// - Returns: The view the function is attached to | ||
func onToastNotification<ToastNotification: Identifiable>(perform action: @escaping (ToastNotification?) -> Void) -> some View { | ||
onReceive(NotificationCenter.default.publisher(for: .toastNotification)) { | ||
action($0.object as? ToastNotification) | ||
} | ||
} | ||
} |