How to grab the NEXT fire date from a UILocalNotification object

前端 未结 4 764
[愿得一人]
[愿得一人] 2020-12-06 08:13

I have a UILocalNotification object that I have setup with repeat intervals day, week, and month. I am having no troubles at all accessing the fire date of the object:

4条回答
  •  情书的邮戳
    2020-12-06 08:52

    This is in Swift 4 and using calendar's nextDate func.

    extension UILocalNotification {
    
        var nextFireDate: Date? {
            guard let fireDate = fireDate else { return nil }
    
            let today = Date()
            let cal = Calendar.current
    
            if fireDate.compare(today) == .orderedDescending {
                return fireDate
            }
    
            let s: Set
            switch repeatInterval {
            case .year: s = [.month, .day, .hour, .minute, .second]
            case .month: s = [.day, .hour, .minute, .second]
            case .day: s = [.hour, .minute, .second]
            case .hour: s = [.minute, .second]
            case .minute: s = [.second]
            default: return nil // Not supporting other intervals
            }
    
            let components = cal.dateComponents(s, from: fireDate)
            return cal.nextDate(after: today, matching: components, matchingPolicy: .nextTimePreservingSmallerComponents)
        }
    
    }
    

提交回复
热议问题