Skip to content

Instantly share code, notes, and snippets.

@jaspermayone
Created October 21, 2024 22:42
Swift Notification Manager
//
// NotificationManager.swift
// To-Bee Done
//
// Created by Jasper Mayone on 10/21/24.
//
import Foundation
import UserNotifications
class NotificationManager {
// TODO: properly handle errors / classes for permission check.
static let shared = NotificationManager()
private init() {} // This ensures the class can't be instantiated outside of `shared`
func checkForPermission() {
let notificationCenter = UNUserNotificationCenter.current()
notificationCenter.getNotificationSettings { settings in
switch settings.authorizationStatus {
case .authorized:
return
case .denied:
return
case .notDetermined:
notificationCenter
.requestAuthorization(
options: [.alert, .sound, .badge]) { didAllow, error in
if didAllow {
return
}
}
default:
return
}
}
}
func dispatchNotification(
title: String,
date: Date
) {
let uuid = UUID().uuidString
// let date = Date().addingTimeInterval(5)
let body = "Task due at \(date)"
let notificationCenter = UNUserNotificationCenter.current()
let content = UNMutableNotificationContent()
content.title = title
content.body = body
content.sound = .default
let dateComponents = Calendar.current.dateComponents(
[.year, .month, .day, .hour, .minute, .second],
from: date
)
let trigger = UNCalendarNotificationTrigger(
dateMatching: dateComponents,
repeats: false
)
let request = UNNotificationRequest(
identifier: uuid,
content: content,
trigger: trigger
)
notificationCenter.add(request) { (error) in
return
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment