Я сделал приложение, которое отправляет локальное уведомление, показывающее пользователю случайное простое число каждый день в 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)
(Не) связанный :