首页 文章

iOS如何按天,周和小时Swift创建计划本地通知

提问于
浏览
0

我想为用户创建一个时间表,现在,我知道如何创建一个特定的时间,但我想创建这样的通知,例如在不同的日子里,或者只为周末,或者用户设置的日子 . 我的每小时通知代码:

var notifTime = Int()
var notifMin = Int()

func test() {
    let content = UNMutableNotificationContent()
      content.title = "Test"
        content.body = "It's test bro"
        content.sound = UNNotificationSound.default()

        let gregorian = Calendar(identifier: .gregorian)
        let now = Date()
        var components = gregorian.dateComponents([.year, .month, .day, .hour, .minute, .second], from: now)

        components.hour = notifTime
        components.minute = notifMin
        components.second = 0

        let date = gregorian.date(from: components)!

        let triggerDaily = Calendar.current.dateComponents([.hour,.minute,.second,], from: date)
        let trigger = UNCalendarNotificationTrigger(dateMatching: triggerDaily, repeats: true)

        let request = UNNotificationRequest(identifier: "any", content: content, trigger: trigger)
        UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)
}

对于时间提取我使用日期选择器 .

enter image description here

那么我如何每天创建日程安排通知?

1 回答

  • 0
    let startDate = Date()
    let triggerDate = Calendar.current.dateComponents([.weekday,.hour,.minute], from: startDate)
    

    startDate 设置为第一个通知时间日期 . 希望它对你有用 .

相关问题