如何解决Swiftui:通过函数以编程方式显示警报弹出窗口
我有一个可以在我的应用程序中的几个不同位置调用的函数。
实质上,它检查通知授权状态的状态。如果它是“授权的”,就可以了,该功能什么也不做。如果未确定,则提示用户进行授权。因为没有通知权限,该应用程序将无法100%正常运行,所以我想提醒用户,这是必需的。一切都按计划进行,只是试图找出一种方法来向用户发出警报(即转到“设置”>“通知”>“),或直接定向到应用程序中的另一个页面。
我尝试通过在函数中调用该页面来定向页面,并尝试直接在函数中显示警报,但是据我了解,这两个选项都必须与视图绑定。
该应用在首次启动和安装时会要求获得通知权限,因此大多数问题都不是问题。但是,为了保护我,我想做以上事情。
编辑/更新:
import SwiftUI
struct ContentView: View {
@State var showAlert = false
// FUNCTION: Ask for Notification Permissions
func notificationPermissions() {
UNUserNotificationCenter.current().getNotificationSettings { (settings) in
if settings.authorizationStatus == .authorized {
// Notifications are authorized
print("Notifications are AUTHORIZED")
}
else if settings.authorizationStatus == .denied {
// ALERT: Notifications are denied
print("ALERT: Notifications are DENIED")
self.showAlert = true
print(self.showAlert) // Even though above it is set to true,the print statement says false,the alert doesn't display
}
else {
// Notifications are notDetermined
print("Notifications are NOTDETERMINED")
UNUserNotificationCenter.current().requestAuthorization(options: [.alert,.badge,.sound]) { success,error in
if success {
print("User has accepted Notification Permissions")
} else if let error = error {
print(error.localizedDescription)
}
}
}
}
}
// FUNCTION: Display Notification Reminder Alert
func notificationReminder() -> Alert {
Alert(
title: Text("Notifications Required"),message: Text("Please authorize notifications by going to Settings > Notifications > Remindr"),dismissButton: .default(Text("Okay")))
}
从另一个角度看...
struct newRemindr: View {
// Alert Control
@Binding var showAlert: Bool
@State var notification = ""
var contentView = ContentView()
// View Controller
var body: some View {
NavigationView {
Form {
TextField("Write your notification...",text: $notification)
Button(action: {
self.contentView.notificationPermissions() // Calls the function above from the content view
}) {
Text("Submit")
}
}
}
}
解决方法
您可以在应用程序的alert
(根视图)中使用ContentView
修饰符。
struct ContentView: View {
// pass this var as binding to other views
@State var showAlert = false
func notificationReminder() -> Alert {
Alert(
title: Text("Notifications Required"),message: Text("Please authorize notifications by going to Settings > Notifications > Remindr"),dismissButton: .default(Text("Okay")))
}
var body: some View {
VStack {
Text("this is my main view")
}
.alert(isPresented: self.$showAlert,content: { self.notificationReminder() })
}
}
您可以在应用程序的任何位置显示该警报。您只需将showAlert
设置为true。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。