SwiftUI使用Toggle控制本地通知出现重复推送问题求解
问题根因
你的猜测完全正确,问题出在两点:
- 每次开启开关时都使用
UUID().uuidString生成随机的通知请求ID,系统会把每次提交的请求判定为独立的定时任务,所以开关开启多少次就会留存多少个任务,到点同时触发 - 开关关闭时没有移除对应的定时通知请求,也没有做重复请求的去重判断
修复方案
核心修改点
- 给这个15点的定时通知设置固定的唯一标识符,不要用随机UUID,相同ID的请求提交时会自动覆盖旧的同ID请求
- 开关切换为关闭状态时,根据固定ID移除对应的定时通知请求
- 把通知授权请求提前到页面首次加载时调用,不要每次加通知都重复申请权限
修改后的完整代码
import SwiftUI import UserNotifications struct trial: View { @AppStorage("3") var three = false // 固定通知唯一ID,全局唯一即可 private let notify3PMID = "com.yourapp.3PMDailyNotification" func add3PMNotify() { let content = UNMutableNotificationContent() content.title = "It is 3pm" content.subtitle = "Read the Prime Hour" content.sound = UNNotificationSound(named: UNNotificationSoundName(rawValue: "notifysound.wav")) var dateComponents = DateComponents() dateComponents.hour = 15 dateComponents.minute = 00 dateComponents.second = 00 let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: true) // 用固定ID替代随机UUID let request = UNNotificationRequest(identifier: notify3PMID, content: content, trigger: trigger) UNUserNotificationCenter.current().add(request) } func remove3PMNotify() { // 开关关闭时移除对应ID的待触发通知 UNUserNotificationCenter.current().removePendingNotificationRequests(withIdentifiers: [notify3PMID]) } @State private var name: String = "Tim" var body: some View { VStack { Toggle(isOn: $three) { Text("3 pm") } .padding(.horizontal) .onChange(of: three) { newValue in if newValue { add3PMNotify() } else { remove3PMNotify() } } .onAppear { // 页面首次加载时统一申请通知权限,只需申请一次 UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { success, error in if success { print("All set!") } else if let error = error { print(error.localizedDescription) } } } } } } struct trial_Previews: PreviewProvider { static var previews: some View { trial() } }
可选严谨优化
如果需要避免重复添加的冗余操作,可以在添加通知前先查询待触发列表,确认同ID通知不存在后再添加:
func add3PMNotify() { let center = UNUserNotificationCenter.current() center.getPendingNotificationRequests { requests in // 判断同ID通知是否已经存在 let isExisted = requests.contains { $0.identifier == self.notify3PMID } guard !isExisted else { return } // 不存在再生成请求添加 let content = UNMutableNotificationContent() content.title = "It is 3pm" content.subtitle = "Read the Prime Hour" content.sound = UNNotificationSound(named: UNNotificationSoundName(rawValue: "notifysound.wav")) var dateComponents = DateComponents() dateComponents.hour = 15 dateComponents.minute = 00 dateComponents.second = 00 let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: true) let request = UNNotificationRequest(identifier: self.notify3PMID, content: content, trigger: trigger) center.add(request) } }
内容的提问来源于stack exchange,提问作者Code Beast
相关产品推荐
相关产品推荐

