嗨,我想为类似WhatsApp的通话显示通知 我试图通过计时器制作它,但是没用
self.timer = Timer.init(timeInterval: 5.0, repeats: true, block: { (timer) in
DispatchQueue.main.async {
self.scheduleLocalNotification(nameLocatino: myString)
}})
答案 0 :(得分:0)
您必须使用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,因此它计算即将到来的日期 上面的代码将在5秒间隔内发布10条通知 您需要使用上面的代码计算最长时间(最后输入日期)并安排通知时间