简体   繁体   English

我如何在首次启动后请求用户许可发送本地通知?

[英]How do I ask the user for permission to send local notifications after initial launch?

I would like to use local notifications in my SwiftUI app, but I need to get the user's permission first. 我想在我的SwiftUI应用程序中使用本地通知,但是我需要先获得用户的许可。 On Apple's documentation, however, I only see information about asking permission when the app first opens. 但是,在Apple的文档中,我仅在应用程序首次打开时看到有关询问权限的信息。

I have a setup sequence that happens when you first open the app that guides the user through setting their preferences, one of which is notifications. 我有一个设置序列,该序列在您首次打开该应用程序时发生,该应用程序指导用户设置其首选项,其中之一是通知。

My setup so far is to have the user press "Continue" on the previous screen (NotifPermissionScreen, see below) then be taken to a blank screen where the only thing asked is notification preference. 到目前为止,我的设置是让用户在上一个屏幕(NotifPermissionScreen,请参阅下文)上按“继续”,然后进入空白屏幕,其中唯一需要询问的是通知首选项。 After this, I would like to load in different views depending on if they allowed notifications or not. 之后,我想根据它们是否允许通知来加载不同的视图。

Any help would be greatly appreciated! 任何帮助将不胜感激! :) :)

I'm using Xcode 11 beta 3 and I'm making my app in SwiftUI. 我正在使用Xcode 11 beta 3,并且正在SwiftUI中制作我的应用程序。

struct NotifPermissionScreen : View {
    var body: some View {

        // Show notification preference message


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

// NOTE: I have no idea if notificationsAllowed is a real variable, but this code represents the general structure of what I'm trying to do //注意:我不知道notificationsAllowed是否是一个真实的变量,但是这段代码代表了我想要做的一般结构

I ended up figuring it out! 我最终弄清楚了! Here's what I did: 这是我所做的:

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()
        }
    }
}

If anyone needs any clarification on how this works, please let me know! 如果有人需要任何说明,请告诉我! :) :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM