跟踪是否触发通知

时间:2020-04-24 01:20:43

标签: swift swiftui

我有这个:

import SwiftUI  
import UserNotifications  

struct ContentView: View {  

    var body: some View {  
        VStack {  
            Button("Request Permission") {  
                RequestNotificationsAccess()  
            }  

            Button("Schedule Notification") {  
                ScheduleNotification()  
            }  
        }  
    }  
}  

func RequestNotificationsAccess() {  
    UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { success, error in  
        if success {  
            print("All set!")  
        } else if let error = error {  
            print(error.localizedDescription)  
        }  
    }  
}  

func ScheduleNotification() {  
    let content = UNMutableNotificationContent()  
    content.title = "Title:"  
    content.subtitle = "some text"  
    content.sound = UNNotificationSound.default  

    // show this notification five seconds from now  
    let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false)  

    // choose a random identifier  
    let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: trigger)  

    // add our notification request  
    UNUserNotificationCenter.current().add(request)  
}  

效果很好,但是当我多次单击按钮时,通知会多次出现,如何跟踪它是否已被触发,如果是,则不显示任何内容?

谢谢

1 个答案:

答案 0 :(得分:0)

好,要使先前的通知不显示,请在安排另一个通知之前尝试执行以下操作:

UNUserNotificationCenter.current().removeAllPendingNotificationRequests() 

或跟踪ID并使用

removeDeliveredNotifications(withIdentifiers:)"