Содержимое локального уведомления передается в al oop in iOS - PullRequest
0 голосов
/ 21 июня 2020

Я пытаюсь реализовать локальные уведомления в своем приложении. Идея состоит в том, что пользователю отправляется уведомление каждый день в 9:00 с другой цитатой, но я столкнулся с ошибкой, при которой всегда отображается одно и то же содержимое уведомления, т.е. одна и та же цитата повторяется бесконечно. Как я мог это исправить? Это код, который я использую, и я пытался использовать 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])
        }
    }

1 Ответ

0 голосов
/ 21 июня 2020

Проблема здесь в том, что для триггера установлено значение «Истина» для повторов.

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

Вам нужно будет установить для него значение false и повторно запускать этот метод каждый раз, когда вы хотите запланировать разные уведомление (другое содержимое)

Чтобы получать уведомление, когда приложение находится на переднем плане, вам необходимо реализовать метод willPresent из UNUserNotificationCenterDelegate

Вот простой пример:

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])
    }
}

...