我对SwiftUI还比较陌生,希望能得到一些帮助。我正在编写一个应用程序,并希望用户与通知进行交互。如果他们“Okay”了通知,我想改变视图的一部分,这里只是一个随着每个“Okay”而增加的计数器。
我的问题在于,我无法在视图之外使用@State var notificationCounter,因此它不能自动更新视图。但是,当我将@State var notificationCounter输入视图时,由于作用域的原因,我的函数userNotificationCenter无法访问该变量。
有什么解决方法吗?
以下是我目前的代码:
以下是我目前的代码:
import SwiftUI
import UserNotifications
var notificationCounter = 0
struct HomeScreenView: View {
// @State var notificationCounter = 0
@State var delegate = NotificationDelegate()
var body: some View {
ZStack {
Color("Nice Green")
.ignoresSafeArea()
VStack {
Button(action:
createNotification,
label: {
Text("Notify User")
})
.onAppear(perform: { //request permissions
UNUserNotificationCenter.current().requestAuthorization(options: [.alert,.badge,.sound]) {(_,_) in
}
UNUserNotificationCenter.current().delegate = delegate
})
Text("Notification Interactions \(notificationCounter)")
}
}
}
func createNotification() {
let content = UNMutableNotificationContent()
content.title = "God of Posture"
content.subtitle = "Straighten Your Neck"
content.categoryIdentifier = "Actions"
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 4, repeats: false)
let request = UNNotificationRequest(identifier: "In-App", content: content, trigger: trigger)
//notification actions
let close = UNNotificationAction(identifier: "Close", title: "Close", options: .destructive)
let okay = UNNotificationAction(identifier: "Okay", title: "Okay", options: .destructive)
let category = UNNotificationCategory(identifier: "Actions", actions: [close, okay], intentIdentifiers: [], options: [])
UNUserNotificationCenter.current().setNotificationCategories([category])
UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)
}
struct HomeScreenView_Previews: PreviewProvider {
static var previews: some View {
ContentView().previewDevice(PreviewDevice(rawValue: "iPhone X"))
}
}
}
class NotificationDelegate: NSObject, ObservableObject, UNUserNotificationCenterDelegate {
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
completionHandler([.badge, .banner, .sound])
}
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
if response.actionIdentifier == "Okay" {
print("Hello")
print("counter is " + String(notificationCounter))
notificationCounter = notificationCounter + 1
print("counter is now " + String(notificationCounter))
}
completionHandler()
}
}