Отправка push уведомлений по расписанию, которое выбрал юзер

Хочу сделать отправку пуш уведомлений по расписанию, которое задает сам юзер. В AppDelegate написал:

import UIKit
import UserNotifications

class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {
func registerForPushNotifications() {
  UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) {
    (granted, error) in
    print("Permission granted: \(granted)")

    guard granted else { return }
    self.getNotificationSettings()
    self.createNotification()
  }
}

func getNotificationSettings() {
  UNUserNotificationCenter.current().getNotificationSettings { (settings) in
    print("Notification settings: \(settings)")
    guard settings.authorizationStatus == .authorized else { return }
    UIApplication.shared.registerForRemoteNotifications()
  }
}

func createNotification() {
    let content = UNMutableNotificationContent()
    content.title = "Test Notification"

    //Триггер на уведомления (в секундах)
    let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 3600, repeats: true)
    
    let request = UNNotificationRequest(identifier: "Notification", content: content, trigger: trigger)
    // UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)
         UNUserNotificationCenter.current().add(request) { (error) in
             if error != nil {
                 print("Add notification error: \(String(describing: error?.localizedDescription))")
             }
         }
    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
        print("did recieve notif")
    }
    
    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        completionHandler([.alert, .sound, .badge])
    }
}
 
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
  let tokenParts = deviceToken.map { data -> String in
    return String(format: "%02.2hhx", data)
  }
  
  let token = tokenParts.joined()
  print("Device Token: \(token)")
}

func application(_ application: UIApplication,
                 didFailToRegisterForRemoteNotificationsWithError error: Error) {
  print("Failed to register: \(error)")
}

}

Есть View, где юзер выбирает время, когда ему надо будет отправлять уведомления (например, с 9 утра). Выбор идет с DatePicker'a.

class ModalFromVC: UIViewController {
    
    let dateFormatter = DateFormatter()
    
    @IBOutlet weak var datePickerOutlet: UIDatePicker!
    @IBOutlet weak var currentTimeOutlet: UILabel!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        currentTimeOutlet.text = "Уведомления отправляются с: \(UserSettings.userNotifFrom ?? " ")"
    }
    
    
    @IBAction func saveButtonTapped(sender: UIButton) {
        DispatchQueue.main.async {
            //let timeNotifFrom: Date = self.datePickerOutlet.date
            self.dateFormatter.dateFormat = "HH:mm"
            UserSettings.userNotifFrom = self.dateFormatter.string(from: self.datePickerOutlet.date)
            let content = UNMutableNotificationContent()
            content.title = "Test Notif"
            //часы переводим в секунды
            let trigger = UNTimeIntervalNotificationTrigger(timeInterval: Double(UserSettings.userNotifFrom)! * 3600, repeats: true)
            let request = UNNotificationRequest(identifier: "notificationStart", content: content, trigger: trigger)
            UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)
            self.currentTimeOutlet.text = "Уведомления отправляются с: \(UserSettings.userNotifFrom!)"
        }
    }
    
    @IBAction func cancelPressed(_ sender: UIBarButtonItem) {
        dismiss(animated: true, completion: nil)
    }
}

Вопрос: как сделать расписание отправки пуш уведомлений? Чтобы пуши отправлялись только, например, только с 9-18 часов с интервалом, которое тоже выбирает юзер.


Ответы (0 шт):