【问题标题】:How do I ask the user for permission to send local notifications after initial launch?如何在初始启动后请求用户允许发送本地通知?
【发布时间】:2019-07-09 09:24:38
【问题描述】:

我想在我的 SwiftUI 应用中使用本地通知,但我需要先获得用户的许可。然而,在 Apple 的文档中,我只看到有关在应用首次打开时询问权限的信息。

我有一个设置顺序,当您第一次打开应用程序时会发生,该应用程序会引导用户设置他们的偏好,其中之一是通知。

到目前为止,我的设置是让用户在前一个屏幕(NotifPermissionScreen,见下文)上按“继续”,然后进入一个空白屏幕,其中唯一询问的是通知首选项。在此之后,我想根据它们是否允许通知来加载不同的视图。

任何帮助将不胜感激! :)

我正在使用 Xcode 11 beta 3,并且正在使用 SwiftUI 制作我的应用程序。

struct NotifPermissionScreen : View {
    var body: some View {

        // Show notification preference message


        if (notificationsAllowed) {
            SetupScreen3()
        } else {
            SetupScreen4()
        }
    }
}

// 注意:我不知道 notifyAllowed 是否是一个真正的变量,但这段代码代表了我正在尝试做的一般结构

【问题讨论】:

  • 非常感谢。您是否会偶然知道如何在代码中修改 BindableObject 实例的属性?

标签: ios swift notifications swiftui


【解决方案1】:

我终于弄明白了!这是我所做的:

var body: some View {
    if !hasPressedNotifButton {
        Button(action: {

            // Request permission to send notifications
            self.center.requestAuthorization(options: [.alert, .sound])
            { (granted, error) in

                // Hide this button by setting this @State variable to true
                self.hasPressedNotificationsButton = true

                if granted {
                    // Edit the user's data for later use
                    self.userData.wantsNotifications = true
                }
            }
        }) {
            Text("Set Notifications")
        }
        if self.userData.wantsNotifications {
            WantsNotifsView()
        } else {
            NoNotifsView()
        }
    }
}

如果有人需要任何有关其工作原理的说明,请告诉我! :)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-02-20
    • 2018-03-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-05
    相关资源
    最近更新 更多