NotificationManager.swift 1.99 KB
//
//  NotificationManager.swift
//  Pro-Seecurity-VPN
//
//  Created by Artem Talko on 29.11.2023.
//
import UIKit
import UserNotifications

final class NotificationManager {
    private let notificationInterval: TimeInterval = 60 * 4 * 60

    init() {
        chechForPermission()
    }
    
    private func chechForPermission() {
        let notificationCenter = UNUserNotificationCenter.current()
        
        notificationCenter.getNotificationSettings { settings in
            switch settings.authorizationStatus {
            case .authorized:
                self.dispatchNotification()
                
            case .notDetermined:
                notificationCenter.requestAuthorization(options: [.alert, .sound]) { didAllow, error in
                    if didAllow {
                        self.dispatchNotification()
                    }
                }
                
            case .denied:
                return
                
            default:
                return
            }
        }
    }
    
    private func generateRandomNotificationBody() -> String {
        return StringConstants.notificationMessages.randomElement() ?? ""
    }
    
    private func dispatchNotification() {
        guard !CachingManager.shared.isSubscriptionActive else {
            return
        }

        let identifier = StringConstants.notificationIdentifier
        let notificationCenter = UNUserNotificationCenter.current()
        
        let content = UNMutableNotificationContent()
        content.title = StringConstants.notificationTitle
        content.body = generateRandomNotificationBody()
        content.sound = .default
        
        let trigger = UNTimeIntervalNotificationTrigger(timeInterval: notificationInterval, repeats: true)
        let request = UNNotificationRequest(identifier: identifier, content: content, trigger: trigger)
        
        notificationCenter.removePendingNotificationRequests(withIdentifiers: [identifier])
        notificationCenter.add(request)
    }
}