如何在后台每 5 秒重复一次本地通知

How to repeat local notification every 5 sec in background

嗨,我想显示 WhatsApp 等来电的通知 我试图通过定时器实现,但没有成功

self.timer = Timer.init(timeInterval: 5.0, repeats: true, block: { (timer) in
DispatchQueue.main.async {                       
   self.scheduleLocalNotification(nameLocatino: myString)                                
}})

你必须使用 NSCalendarNotifiationTrigger

你的例子

      var date = Date()
    let notificationCenter = UNUserNotificationCenter.current()
    for i in 0...10 {
    let content = UNMutableNotificationContent()
    content.title = "Title\(i)"
    content.body = "Body"
    var dateComponents = DateComponents()
    dateComponents.calendar = Calendar.current
    let secondsToAdd = 5
    dateComponents.second = secondsToAdd
    guard let futureDate = dateComponents.calendar?.date(byAdding: dateComponents, to: date),
        let futureDateComponents = dateComponents.calendar?.dateComponents([.day, .hour, .minute, .second], from: futureDate) else { return }
        date = futureDate
    print(futureDate)
    // Create the trigger as a repeating event.
    let trigger = UNCalendarNotificationTrigger(
        dateMatching: futureDateComponents, repeats: false)
    // Create the request
    let notificationIdentifier = "notification\(i)seconds" // you can use this indentifier if you want to cancel a notification
    let request = UNNotificationRequest(identifier: notificationIdentifier,
                                        content: content, trigger: trigger)
    // Schedule the request with the system.
    notificationCenter.add(request) { (error) in
        if error != nil {
            // Handle any errors.
        }
    }
}

其中 secondsToAdd 为 5,因此它计算即将到来的日期 上面的代码将 post 以 5 秒为间隔发送 10 次通知 您需要使用上述代码计算最长时间(最后输入日期)和安排通知