代码之家  ›  专栏  ›  技术社区  ›  Said-Abdulla Atkaev

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

  •  1
  • Said-Abdulla Atkaev  · 技术社区  · 7 年前

    例如,如何运行本地通知? 在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 回复  |  直到 7 年前
        1
  •  2
  •   shallowThought    7 年前

    有一个重复功能。

    从…起 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
    }
    

    通知每分钟发布一次: