You need to enable JavaScript to run this app. SwiftUI使用Toggle控制本地通知出现重复推送问题求解
优惠活动
大模型
产品
解决方案
定价
更多

SwiftUI使用Toggle控制本地通知出现重复推送问题求解

问题根因

你的猜测完全正确,问题出在两点:

  • 每次开启开关时都使用UUID().uuidString生成随机的通知请求ID,系统会把每次提交的请求判定为独立的定时任务,所以开关开启多少次就会留存多少个任务,到点同时触发
  • 开关关闭时没有移除对应的定时通知请求,也没有做重复请求的去重判断
修复方案

核心修改点

  1. 给这个15点的定时通知设置固定的唯一标识符,不要用随机UUID,相同ID的请求提交时会自动覆盖旧的同ID请求
  2. 开关切换为关闭状态时,根据固定ID移除对应的定时通知请求
  3. 把通知授权请求提前到页面首次加载时调用,不要每次加通知都重复申请权限

修改后的完整代码

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.21 13:15:09