You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

iOS每日本地通知开发求助:实现每周循环、每日不同内容的定时推送

解决每周循环的每日个性化早安本地通知问题

Hey there! 给女友做周年纪念APP这个想法真的超暖心🥰,我来帮你搞定这个本地通知的需求,让每天的早安问候都不一样,还能每周精准循环对应日期的内容~

核心思路

要实现「每周一到周日不同内容、每天8点推送、每周循环」的效果,我们需要为周一到周日分别创建独立的通知请求——因为UNCalendarNotificationTrigger的重复逻辑是基于你设置的日期组件匹配规则,所以单独为每个工作日配置触发器和对应内容,就能实现每周循环对应消息的效果。

完整实现代码

我把代码整理成了一个便于管理的单例类,你可以直接集成到项目中:

import UserNotifications

class NotificationManager {
    // 单例模式,全局统一管理通知
    static let shared = NotificationManager()
    private let notificationCenter = UNUserNotificationCenter.current()
    
    // 私有初始化,避免外部创建实例
    private init() {}
    
    // 第一步:请求用户的通知权限
    func requestNotificationPermissions() {
        notificationCenter.requestAuthorization(options: [.alert, .sound, .badge]) { granted, error in
            if let error = error {
                print("请求通知权限出错:\(error.localizedDescription)")
            } else if granted {
                print("用户已允许通知权限")
            } else {
                print("用户拒绝了通知权限,无法推送早安问候")
            }
        }
    }
    
    // 第二步:配置每周循环的早安通知
    func setupWeeklyMorningGreetings() {
        // 定义周一到周日的专属问候语(注意:iOS中weekday=1是周日,2是周一,以此类推到7是周六)
        let dailyGreetings = [
            "Sleep in a little today...you deserve it! Love you <3", // 周日(weekday=1)
            "Good morning!", // 周一(weekday=2)
            "I hope you have a great day!", // 周二(weekday=3)
            "Make sure to take care of yourself today!", // 周三(weekday=4)
            "Just wanted to say I'm thinking of you nonstop!", // 周四(weekday=5)
            "Counting down the minutes until I see you tonight!", // 周五(weekday=6)
            "Let's have a lazy, perfect weekend together! 💖" // 周六(weekday=7)
        ]
        
        // 先清除已有的待发送通知请求,避免重复添加导致同一天收到多条通知
        notificationCenter.removeAllPendingNotificationRequests()
        
        // 循环创建每个工作日的通知
        for (index, greeting) in dailyGreetings.enumerated() {
            // 配置通知内容
            let content = UNMutableNotificationContent()
            content.title = "Good Morning princess :)"
            content.body = greeting
            content.sound = .default // 启用默认提示音
            
            // 配置触发条件:每天8点整,对应每周的某一天
            var dateComponents = DateComponents()
            dateComponents.hour = 8
            dateComponents.minute = 0
            dateComponents.weekday = index + 1 // 索引从0开始,对应weekday=1到7
            
            // 创建每周重复的触发器
            let trigger = UNCalendarNotificationTrigger(
                dateMatching: dateComponents,
                repeats: true
            )
            
            // 为每个通知设置唯一标识符,方便后续修改/删除
            let request = UNNotificationRequest(
                identifier: "MorningGreeting_Weekday\(index + 1)",
                content: content,
                trigger: trigger
            )
            
            // 添加通知请求到系统
            notificationCenter.add(request) { error in
                if let error = error {
                    print("添加周\(index + 1)通知失败:\(error.localizedDescription)")
                } else {
                    print("周\(index + 1)的早安通知已成功配置")
                }
            }
        }
    }
}

如何调用代码

你需要在APP启动时请求权限,并在用户同意后配置通知。比如在AppDelegatedidFinishLaunchingWithOptions方法中:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    // 请求通知权限
    NotificationManager.shared.requestNotificationPermissions()
    
    // 延迟1秒调用配置方法(确保权限请求流程完成),也可以在权限回调的granted=true分支里直接调用
    DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
        NotificationManager.shared.setupWeeklyMorningGreetings()
    }
    
    return true
}

关键细节说明

  • Weekday的对应规则:iOS的DateComponents.weekday属性,1代表周日,2代表周一,直到7代表周六,所以数组的索引要和这个规则对应上。
  • 唯一标识符:每个通知的identifier必须唯一,这样后续如果需要修改某一天的问候语,或者删除特定日期的通知,都可以通过这个ID操作。
  • 清除已有请求:在添加新通知前调用removeAllPendingNotificationRequests(),可以避免重复添加同一通知,导致用户同一天收到多条重复消息。
  • Info.plist配置:别忘了在项目的Info.plist中添加NSUserNotificationUsageDescription(iOS 10+),填写请求通知权限的理由(比如"为了给你推送专属早安问候"),否则APP会崩溃或者用户看不到权限请求弹窗。

希望这个方案能帮你完成APP的最后一步,祝你们周年快乐!🥳

内容的提问来源于stack exchange,提问作者jesse bui

火山引擎 最新活动