iOS 中进入循环的本地通知内容

Local Notification content going into a loop in iOS

我正在尝试在我的应用程序中实现本地通知。这个想法是每天在 9:00 a.m 向用户发送通知。有不同的引述,但我遇到了一个错误,其中始终显示相同的通知内容,即无休止地重复相同的引述。我该如何解决?这是我正在使用的代码,我尝试为发送的每个通知使用 UUID,但它没有带来改进。

    let notificationCenter = UNUserNotificationCenter.current()
    let options: UNAuthorizationOptions = [.alert, .sound]
    notificationCenter.requestAuthorization(options: options) {
        (didAllow, error) in
        if !didAllow {
            print("User has declined notifications")
        }
    }

    notificationCenter.getNotificationSettings { (settings) in
      if settings.authorizationStatus != .authorized {
        print("Notifications not allowed")
      }
    }
    
    let randomArrayNotificationQuote = Int(arc4random_uniform(UInt32(myQuotes.count)))
    let randomArrayNotificationTitle = Int(arc4random_uniform(UInt32(myTitle.count)))
    
    let content = UNMutableNotificationContent()
    content.title = "\(myTitle[randomArrayNotificationTitle])"
    content.body = "\(myQuotes[randomArrayNotificationQuote])"
    content.sound = UNNotificationSound.default
    content.categoryIdentifier = "com.giovannifilippini.philo"
    
    // Deliver the notification
    
    var dateComponents = DateComponents()
    dateComponents.hour = 9
    dateComponents.minute = 00
    let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: true)
    
    let uuid = UUID().uuidString
    
    let request = UNNotificationRequest.init(identifier: uuid, content: content, trigger: trigger)
    
    notificationCenter.add(request) { (error) in
        if error != nil {
            print("add NotificationRequest succeeded!")
            notificationCenter.removePendingNotificationRequests(withIdentifiers: [uuid])
        }
    }

这里的问题是触发器将重复设置为 true

let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: true)

您需要将其设置为 false 并在每次您想要安排不同的通知时重新 运行 此方法 (不同的内容)

为了在应用程序处于前台时接收通知,您需要从 UNUserNotificationCenterDelegate

中实施 willPresent 方法

这是一个简单的例子:

class ViewController: UIViewController {
    
    private let userNotificaionCenter = UNUserNotificationCenter.current()

    override func viewDidLoad() {
        super.viewDidLoad()
        // 1. Assign the delegate
        userNotificaionCenter.delegate = self
        scheduleNotification()
    }

    func scheduleNotification() {
      // Same notification logic that you have
    }
 }

// 2. Implement the UNUserNotificationCenterDelegate
extension ViewController: UNUserNotificationCenterDelegate {
    
    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        // This will allow the app to receive alerts and sound while in the foreground
        completionHandler([.alert, .sound])
    }
}