重复本地通知而不更新内容

时间:2019-01-13 00:11:08

标签: ios usernotifications

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

(不涉及)

1 个答案:

答案 0 :(得分:1)

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

您基本上有三个选择:

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

我认为我可能会倾向于3,但是我还没有亲自使用该API。它似乎与您想要发生的事情最接近:它本质上是一种回调-尽管是精心设计的-允许您“更新”内容。


*另请参阅:10-minute intro to them(可可豆小叮咬)