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

时间:2018-08-13 06:29:15

标签: ios swift notifications

我想为用户创建时间表,就目前而言,我知道如何创建特定时间,但是我想创建这样的通知,例如分几天或仅在一个周末,或者为哪个用户设置日期。  我的每小时通知代码:

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 :(得分:0)

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

startDate设置为第一个通知时间日期。 希望对您有用。