【问题标题】:Repeating local notification not updating content重复本地通知不更新内容
【发布时间】:2019-06-07 11:15:12
【问题描述】:

我制作了一个应用程序,该应用程序每天上午 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)

(不)相关

【问题讨论】:

    标签: ios usernotifications


    【解决方案1】:

    创建请求后,内容即已修复。如果不是,那么您的UNUserNotificationCenterDelegate 可以使用某种方法来执行此操作。您编写的代码不会因为通知重复而被重新调用。

    你基本上有三个选择:

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

    我想我可能会倾向于 3,但我还没有亲自使用过那个 API。它似乎最接近您想要发生的事情:它本质上是一个回调 - 尽管是一个复杂的回调 - 允许您“更新”内容。


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

    【讨论】:

    • 在我查看您的建议之前,这种行为是正常的吗?重复本地通知无法更新其内容?
    • 是的;至少,我从未见过任何提供它的 API。
    • 嗯好的(坐下,腿发抖),所以: 1. 我需要自己的服务器,还是 Apple 提供这样的东西?如果我需要自己的,我无权访问。 2. 听起来不错。所以我会一次性安排它们,而且基本上不会使用重复通知?但是用户打开应用程序会如何影响呢?它会将数量重置为64?毕竟,如果用户 2 个月没有打开应用程序,他们可能不想要通知...... :) 3. 我玩过,但内容只能在 3D Touch 上看到,我更喜欢避免(但它可能是最好的解决方案)。
    • 1.你需要自己的服务器。 2. 需要用户打开应用才能安排更多通知。如果您安排了 64,然后它们都在没有打开应用程序的情况下交付,您就没有机会安排更多。 3. 不只是 3D 触摸,它也是由用户向下拖动横幅触发的——参见我在底部添加的 Little Bites of Cocoa 链接。
    • 1.好的,不幸的是,这不是一个选择。 3.啊,那也是一种选择。 2.我发现之前某处发布的答案基本上显示了您提供的#2的方式,但我认为数量永远不会重置,并且因为64还不够,所以我将其驳回。现在正在寻找它...也许您可以提供一个示例实现?
    猜你喜欢
    • 1970-01-01
    • 2023-01-05
    • 1970-01-01
    • 2014-05-27
    • 2020-09-19
    • 1970-01-01
    • 2021-05-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多