在“A”上午和“下午”之间每隔x分钟重复一次动作

时间:2017-10-14 09:54:46

标签: ios swift notifications nstimer

如何运行本地通知? 在UNUserNotificationCenter中没有重复功能。 也许使用NSTimer或类似的东西?

为什么我的代码无法正常工作

let hours: [Int] = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24]
    for hour in hours {
        for minute in stride(from: 0, to: 60, by: 5){
            let content = UNMutableNotificationContent()
            content.title = "Title"
            content.body = "Body"

            var dateComponents = DateComponents()
            dateComponents.hour = hour
            dateComponents.minute = minute

            let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: true)
            let request = UNNotificationRequest(identifier: "timerDone", content: content, trigger: trigger)
            let center = UNUserNotificationCenter.current()
            center.add(request) { (error : Error?) in
                if let theError = error {
                    print(theError.localizedDescription)
                }
            }

        }
    }

1 个答案:

答案 0 :(得分:2)

有一个重复的功能。

来自Apple's documentation

let content = UNMutableNotificationContent()
content.title = NSString.localizedUserNotificationString(forKey: 
           "Hello!", arguments: nil)
content.body = NSString.localizedUserNotificationString(forKey: 
           "Hello_message_body", arguments: nil)

// Deliver the notification in five seconds and repeat it
content.sound = UNNotificationSound.default() 
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 60, 
        repeats: true)

// Schedule the notification.
let request = UNNotificationRequest(identifier: "60_seconds", content: content, trigger: trigger) 
let center = UNUserNotificationCenter.current()
center.add(request, withCompletionHandler: nil)

修改

正如文档中所写,您当然必须拥有发布通知的用户权限:

let center = UNUserNotificationCenter.current()
center.requestAuthorization(options: [.alert, .sound]) { (granted, error) in
    // Enable or disable features based on authorization
}

<强>结果:

通知每分钟发布一次: