iOS中使用RunLoop + Timer实现定时提醒功能

703 阅读1分钟

最近项目上有个需求需要在指定时间让app去做一件事情,一开始想过注册一个 本地通知 UserNotifications 是最简单直接的一个方法。但因为不需要弹显示的通知,在验证后发现使用UserNotification去schedule一个local通知必须带消息才会被触发,于是只能使用Timer 来实现。

Timer

使用 Timer 去schedule一个指定时间的事件,fireDate设在每天的下午5点钟:

        let calendar = Calendar.current
        var dateComponents = calendar.dateComponents(
        [.calendar, .timeZone,
         .era, .quarter,
         .year, .month, .day,
         .hour, .minute, .second, .nanosecond,
         .weekday, .weekdayOrdinal,
         .weekOfMonth, .weekOfYear, .yearForWeekOfYear],
        from: Date())
        let currentDate = dateComponents.date ?? Date()
        dateComponents.hour = 17
        dateComponents.minute = 0
        dateComponents.second = 0
        dateComponents.nanosecond = 0
        let fireDate = dateComponents.date
        let timer = Timer.init(fire: fireDate, interval: 0, repeats: false, block: { (timer) in
                timer.invalidate()
                // Actions
            })

RunLoop

把这个Timer加到RunLoop上去:

RunLoop.main.add(timer, forMode: .commonModes)

这样就可以在指定时间执行某个功能了。

为了对RunLoop的机制理解的更透彻一点,看了两篇介绍RunLoop的文章,都写的挺不错的。里面有RunLoop在 commonModesdefault 模式下的不同场景应用。

  1. 深入理解RunLoop
  2. 我认为的 Runloop 最佳实践