SwiftUI:如何使通知交互改变视图的一部分?

3
我对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()
        
    }
}
1个回答

0
最简单的解决方案是在你的 NotificationDelegate 上制作一个 @Published 属性(顺便说一下,它应该是 @StateObject,而不是 @State)。
struct HomeScreenView: View {
    @StateObject var delegate = NotificationDelegate()
    
    var body: some View {
        ZStack {
            Color("Nice Green")
                .ignoresSafeArea()
            VStack {
                Button(action: delegate.createNotification) {
                    Text("Notify User")
                }
                .onAppear {
                    delegate.requestAuthorization()
                }
                Text("Notification Interactions \(delegate.notificationCounter)")
            }
        }
    }
}

class NotificationDelegate: NSObject, ObservableObject, UNUserNotificationCenterDelegate {
    
    @Published var notificationCounter = 0
    
    override init() {
        super.init()
        UNUserNotificationCenter.current().delegate = self
    }
    
    func requestAuthorization() {
        UNUserNotificationCenter.current().requestAuthorization(options: [.alert,.badge,.sound]) {(_,_) in
        }
    }
    
    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()
    }
    
    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)
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接