初次启动后如何请求用户允许发送本地通知?
How do I ask the user for permission to send local notifications after initial launch?
我想在我的 SwiftUI 应用程序中使用本地通知,但我需要先获得用户的许可。然而,在 Apple 的文档中,我只看到有关在应用程序首次打开时请求许可的信息。
我有一个设置序列,当您第一次打开应用程序时会发生,该应用程序会引导用户设置他们的首选项,其中之一是通知。
到目前为止,我的设置是让用户在前一个屏幕(NotifPermissionScreen,见下文)上按 "Continue",然后进入空白屏幕,唯一询问的是通知首选项。在此之后,我想加载不同的视图,具体取决于它们是否允许通知。
如有任何帮助,我们将不胜感激! :)
我正在使用 Xcode 11 beta 3,我正在 SwiftUI 中制作我的应用程序。
struct NotifPermissionScreen : View {
var body: some View {
// Show notification preference message
if (notificationsAllowed) {
SetupScreen3()
} else {
SetupScreen4()
}
}
}
// 注意:我不知道 notificationsAllowed 是否是一个真正的变量,但这段代码代表了我正在尝试做的事情的一般结构
我终于搞清楚了!这是我所做的:
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()
}
}
}
如果有人需要澄清这是如何工作的,请告诉我! :)
我想在我的 SwiftUI 应用程序中使用本地通知,但我需要先获得用户的许可。然而,在 Apple 的文档中,我只看到有关在应用程序首次打开时请求许可的信息。
我有一个设置序列,当您第一次打开应用程序时会发生,该应用程序会引导用户设置他们的首选项,其中之一是通知。
到目前为止,我的设置是让用户在前一个屏幕(NotifPermissionScreen,见下文)上按 "Continue",然后进入空白屏幕,唯一询问的是通知首选项。在此之后,我想加载不同的视图,具体取决于它们是否允许通知。
如有任何帮助,我们将不胜感激! :)
我正在使用 Xcode 11 beta 3,我正在 SwiftUI 中制作我的应用程序。
struct NotifPermissionScreen : View {
var body: some View {
// Show notification preference message
if (notificationsAllowed) {
SetupScreen3()
} else {
SetupScreen4()
}
}
}
// 注意:我不知道 notificationsAllowed 是否是一个真正的变量,但这段代码代表了我正在尝试做的事情的一般结构
我终于搞清楚了!这是我所做的:
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()
}
}
}
如果有人需要澄清这是如何工作的,请告诉我! :)