【问题标题】:iOS - Scheduling a repeating notification with different textiOS - 使用不同的文本安排重复通知
【发布时间】:2021-07-14 21:50:12
【问题描述】:

我有一个应用程序,用户需要每天完成一项任务。如果用户没有完成某项任务,他/她会在第二天早上 8 点收到一条提醒,其中包含提示完成任务的短语。

我们想每天早上发送一个短语,但我们不希望它每天都是同一个短语。

这就是我们现在所拥有的:

static func scheduleDailyUnwatchedNotification() {
    
    let notificationMessages = ["Phrase one", "Phrase two", "Phrase 3", "Phrase 4", "Phrase 5"]
    let totalMessages = notificationMessages.count
    let randomIndex = Int.random(in: 0..<totalMessages)
    
    let center = UNUserNotificationCenter.current()
    center.removePendingNotificationRequests(withIdentifiers: ["dailyReminder"])
    
    let content = UNMutableNotificationContent()
    content.title = "Reminder"
    content.body = notificationMessages[randomIndex]
    content.sound = .default
    
    var dateComponents = DateComponents()
    dateComponents.hour = 8
    let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: true)
    
    let request = UNNotificationRequest(identifier: "dailyReminder", content: content, trigger: trigger)
    
    center.add(request)
}

问题在于,即使选择了一个随机短语,通知也会始终以相同的随机短语重复。

我们怎样才能让它用不同的短语重复?

【问题讨论】:

  • 您需要为每一天安排单独的通知,而不是一个重复的通知

标签: ios swift notifications uilocalnotification unnotificationrequest


【解决方案1】:

您需要手动安排每个不同的短语通知。但是,如果您每天都发送一个短语并且您说其中有 50 个,您可以安排每个短语每 50 天重复一次。然后,每当用户打开应用程序时,您总是可以在发送通知的日期前后交换 - 因此短语排序并不总是相同的。这不是最理想的,但确实允许使用不同标题的重复通知。

或者,如果您希望能够在不发布新应用程序的情况下更改通知标题/拥有更多控制权,您可以使用推送通知。通过这种方式,您可以设置一个后端来发送消息,但从服务器的角度来看,它确实有更多的开销。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-08-08
    • 2020-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多