小编典典

3天之内的用户通知,然后每天/每小时重复一次-iOS 10

swift

UILocalNotification已弃用,因此我想将代码更新为UserNotification框架:

let alertDays = 3.0
let alertSeconds = alertDays * 24.0 * 60.0 * 60.0

let localNotification:UILocalNotification = UILocalNotification()

localNotification.alertAction = "Reminder"
localNotification.alertTitle = "Reminder Title"
localNotification.alertBody = "Reminder Message"
localNotification.fireDate = Foundation.Date(timeIntervalSinceNow: alertSeconds)
localNotification.repeatInterval = .day            
UIApplication.shared().scheduleLocalNotification(localNotification)

等待初始通知后,如何通过UserNotification框架设置类似的每日或每小时重复?

let alertDays = 3.0
let alertSeconds = alertDays * 24.0 * 60.0 * 60.0

let content: UNMutableNotificationContent = UNMutableNotificationContent()

content.title = "Reminder Title"
content.subtitle = "Reminder Subtitle"
content.body = "Reminder Message"

let calendar = Calendar.current

let alarmTime = Foundation.Date(timeIntervalSinceNow: alertSeconds)
let alarmTimeComponents = calendar.components([.day, .hour, .minute], from: alarmTime)

let trigger = UNCalendarNotificationTrigger(dateMatching: alarmTimeComponents, repeats: true)

let request = UNNotificationRequest(identifier: workoutAlarmIdentifier,
                                        content: content,
                                        trigger: trigger)

UNUserNotificationCenter.current().add(request)
    {
        (error) in // ...
    }

阅读 298

收藏
2020-07-07

共1个答案

小编典典

似乎不支持此操作,但可以使用以下解决方法:

let alertDays = 3.0
let daySeconds = 86400
let alertSeconds = alertDays * daySeconds

let content: UNMutableNotificationContent = UNMutableNotificationContent()

content.title = "Reminder Title"
content.subtitle = "Reminder Subtitle"
content.body = "Reminder Message"

let trigger = UNTimeIntervalNotificationTrigger.init(timeInterval: (alertSeconds), repeats: false)

let request = UNNotificationRequest(identifier: workoutAlarmIdentifier,
                                    content: content,
                                    trigger: trigger)

UNUserNotificationCenter.current().add(request)
{
    (error) in // ...
}

didReceive(_:withContentHandler
:)
结合使用,您可以使用:

let trigger = UNTimeIntervalNotificationTrigger.init(timeInterval: (daySeconds), repeats: false)

我知道这不是最佳方法,但它应该在不使用不推荐使用的类/方法的情况下工作。您使用重复:false,因为您在用户收到通知之前拦截通知并创建新通知。此外,如果您处理多个通知,则可以将其与UNNotificationAction和UNNotificationCategory结合使用。

2020-07-07