Files
Privado-iOS/iOS/Privado/Sources/Core/Notifications/LocalNotificationsManager.swift

90 lines
3.0 KiB
Swift

//
// LocalNotificationsManager.swift
// PrivadoVPN
//
// Created by Zhandos Bolatbekov on 28.01.2021.
// Copyright © 2021 Privado LLC. All rights reserved.
//
import Foundation
import UIKit
import UserNotifications
final class LocalNotificationsManager: NSObject, UNUserNotificationCenterDelegate {
private let notificationCenter: UNUserNotificationCenter
private weak var application: UIApplication?
private var applicationIconBadgeNumber = 0
// MARK: - Static
private static var instance: LocalNotificationsManager?
static func shared(with notificationCenter: UNUserNotificationCenter = .current()) -> LocalNotificationsManager {
if let manager = instance { return manager }
let instance = LocalNotificationsManager(with: notificationCenter)
self.instance = instance
return instance
}
// MARK: - Init
private init(with notificationCenter: UNUserNotificationCenter) {
self.notificationCenter = notificationCenter
super.init()
self.notificationCenter.delegate = self
}
// MARK: - Interface
func register(for application: UIApplication) {
self.application = application
self.notificationCenter.requestAuthorization(options: [.badge, .sound, .alert]) { granted, _ in
print("Push notifications permission granted: \(granted)")
}
}
func schedule(notification: LocalNotification) {
switch notification.kind {
case .interval:
let request = self.createIntervalNotificationRequest(notification: notification)
self.notificationCenter.add(request) { error in
if let error = error {
print(error.localizedDescription)
}
}
case .calendar, .location:
break
}
}
func resetAppBadgeCount() {
self.applicationIconBadgeNumber = 0
self.application?.applicationIconBadgeNumber = 0
}
// MARK: - UNUserNotificationCenterDelegate
func userNotificationCenter(_ center: UNUserNotificationCenter,
willPresent notification: UNNotification,
withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
completionHandler([.badge, .sound, .alert])
}
// MARK: - Private
private func createIntervalNotificationRequest(notification: LocalNotification) -> UNNotificationRequest {
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 1, repeats: false)
let content = UNMutableNotificationContent()
content.title = notification.title
content.body = notification.body
self.applicationIconBadgeNumber += 1
content.badge = NSNumber(value: self.applicationIconBadgeNumber)
let identifier = UUID().uuidString
let request = UNNotificationRequest(identifier: identifier, content: content, trigger: trigger)
return request
}
}