SpeziNotifications

Build and Test codecov DOI

简化基于 Spezi 的应用程序中的用户通知。

概述

SpeziNotifications 通过向 SwiftUI 视图和 Spezi 模块的环境添加额外的操作,简化了与用户通知的交互。

安排通知

您可以使用 Notifications 模块与应用程序中的用户通知进行交互。您可以将其定义为 Spezi Module 的依赖项,也可以使用 SwiftUI 视图中的 @Environment 属性包装器从环境中检索它。

下面的代码示例安排了一个通知请求,从自定义的 MyNotifications 模块中访问 Notifications 模块。

import Spezi
import UserNotifications


final class MyNotifications: Module {
    @Dependency(Notifications.self)
    private var notifications

    @Application(\.notificationSettings)
    private var settings

    func scheduleAppointmentReminder() async throws {
        let status = await settings().authorizationStatus
        guard status == .authorized || status == .provisional else {
            return // no authorization to schedule notification
        }

        let content = UNMutableNotificationContent()
        content.title = "Your Appointment"
        content.body = "Your appointment is in 3 hours"

        let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 3 * 60, repeats: false)

        let request = UNNotificationRequest(identifier: "3-hour-reminder", content: content, trigger: trigger)

        try await notifications.add(request: request)
    }
}

在 SwiftUI 中请求授权

通知模块和与通知相关的操作也可以在 SwiftUI 环境中使用。下面的代码示例创建了一个简单的通知授权引导视图,该视图 (1) 确定当前的授权状态,以及 (2) 在用户点击按钮时请求通知授权。

import SpeziNotifications
import SpeziViews

struct NotificationOnboarding: View {
    @Environment(\.notificationSettings)
    private var notificationSettings
    @Environment(\.requestNotificationAuthorization)
    private var requestNotificationAuthorization

    @State private var viewState: ViewState = .idle
    @State private var notificationsAuthorized = false

    var body: some View {
        VStack {
            // ...
            if notificationsAuthorized {
                Button("Continue") {
                    // show next view ...
                }
            } else {
                AsyncButton("Allow Notifications", state: $viewState) {
                    try await requestNotificationAuthorization(options: [.alert, .badge, .sound])
                }
                    .environment(\.defaultErrorDescription, "Failed to request notification authorization.")
            }
        }
            .viewStateAlert(state: $viewState)
            .task {
                notificationsAuthorized = await notificationSettings().authorizationStatus == .authorized
            }
    }
}

重要提示

上面的示例使用了 SpeziViews 中的 AsyncButtonViewState 模型,以便更轻松地管理异步操作的状态和处理错误情况。

设置

您需要在 Xcode 中的应用程序Swift 包中添加 SpeziNotifications Swift 包。

许可证

本项目采用 MIT 许可证。有关更多信息,请参阅 许可证

贡献者

本项目由斯坦福大学 Mussallem 生物设计中心开发。有关所有 SpeziNotifications 贡献者的完整列表,请参阅 CONTRIBUTORS.md

Stanford Mussallem Center for Biodesign Logo Stanford Mussallem Center for Biodesign Logo