重复本地通知不更新内容

Repeating local notification not updating content

我制作了一个应用程序,每天早上 9 点发送本地通知,向用户显示一个随机质数。

问题是显示的数字始终相同。
创建通知请求的代码只被调用一次(这是我所期望的,因为通知是重复的),我该如何更新它的内容?

我可以提供生成随机素数的代码,但我已经对其进行了测试并且它有效,所以我认为这不是必需的(否则请告诉我)。

以下是我创建通知请求的方式(来自 AppDelegate):

//  AppDelegate.swift

import UIKit
import MessageUI
import UserNotifications


@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {


    // MARK: Properties

    var window: UIWindow?


    // Life Cycle

    func application(
        _ application: UIApplication,
        didFinishLaunchingWithOptions launchOptions: [
        UIApplication.LaunchOptionsKey: Any]? = nil) -> Bool {

        // MARK: Notification

        // Create notification object
        let center = UNUserNotificationCenter.current()

        // Set the delegate of the Notification to be AppDelegate file
        center.delegate = self

        // Create action allowing user to copy number from notification
        let copyAction = UNNotificationAction(identifier: "COPY_ACTION",
                                              title: "Copy",
                                              options: UNNotificationActionOptions(rawValue: 0))

        // Create category with a copy action
        let myCategory = UNNotificationCategory(identifier: "RANDOM",
                                                actions: [copyAction],
                                                intentIdentifiers: [],
                                                hiddenPreviewsBodyPlaceholder: "",
                                                options: .customDismissAction)

        center.setNotificationCategories([myCategory])

        let options: UNAuthorizationOptions = [.alert, .sound]

        center.requestAuthorization(options: options) { (granted, error) in
            if !granted {
                print("Something went wrong: \(String(describing: error))")
            }
        }

        center.getNotificationSettings { (settings) in
            if settings.authorizationStatus != .authorized {
                // Notifications not allowed
            }
        }

        // Access view controller containing function that generates random prime numbers
        let tab = window?.rootViewController as? UITabBarController
        let randomVC = tab?.viewControllers?[3] as? RandomViewController

        let content = UNMutableNotificationContent()
        content.title = "Your daily prime is:"

        // Set body to random prime, or 1 if returned value is nil
        content.body = "\(randomVC?.makeRandomNotification() ?? 1)"

        content.categoryIdentifier = "RANDOM"
        content.sound = UNNotificationSound(named: UNNotificationSoundName(rawValue: "choo.caf"))

        var date = DateComponents()
        date.hour = 9
        date.minute = 00
        let trigger = UNCalendarNotificationTrigger(dateMatching: date, repeats: true)

        let request = UNNotificationRequest(identifier: "RANDOM", content: content, trigger: trigger)

        center.add(request)

        return true
    }


    func userNotificationCenter(_ center: UNUserNotificationCenter,
                                didReceive response: UNNotificationResponse,
                                withCompletionHandler completionHandler: @escaping () -> Void) {
        switch response.actionIdentifier {
        case "COPY_ACTION":
            UIPasteboard.general.string = response.notification.request.content.body
        default:
            break
        }
        completionHandler()
    }


    func userNotificationCenter(
        _ center: UNUserNotificationCenter,
        willPresent notification: UNNotification,
        withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {

        completionHandler([.alert, .sound])
    }

}

注意:我通过将触发器从特定时间更改为每 60 秒重复一次来对此进行测试。像这样:

let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 60, repeats: true)

(未)相关

一旦您创建了请求,内容就固定了。如果不是,您的 UNUserNotificationCenterDelegate 可以使用一些方法来做到这一点。您编写的代码不会因为通知重复而被重新调用。

你基本上有三个选择:

  1. 使用推送通知而不是本地通知,并将生成新日常内容的责任放在某个服务器中。
  2. 安排许多带有自己素数内容的单独通知(您一次最多可以有 64 个)并依赖于用户在整个过程中在某个时刻打开您的应用两个月,以便您可以安排更多时间。请注意,这意味着您需要代码来确定何时安排了它们,应该添加多少等等。
  3. 创建一个 notification content extension* 允许您在用户看到您的通知并与之互动时选择一个数字。

我想我可能会倾向于 3,但我还没有亲自玩过 API。它似乎最接近你想要发生的事情:它本质上是一个回调——尽管是一个精心设计的回调——让你 "update" 内容。


*另请参阅:10-minute intro to them 在 Cocoa

的 Little Bites