Skip to content

Instantly share code, notes, and snippets.

@st-small
Last active July 5, 2021 14:05
Show Gist options
  • Save st-small/878a2a87917aea0da22772231fc60d4d to your computer and use it in GitHub Desktop.
Save st-small/878a2a87917aea0da22772231fc60d4d to your computer and use it in GitHub Desktop.
Notifications Service Example
public protocol Notificationable {
static var alarmsCache: [String: TimerSound] { get }
static var notificationCenter: UNUserNotificationCenter { get }
static func notificationRequest()
static func checkUsersSettings(completion: @escaping (Bool) -> ())
static func scheduleNotification(alarm: Alarm, interval: TimeInterval)
static func removeNotification(id: String)
static func removeAllPendingNotifications()
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void)
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void)
}
public final class NotificationsServiceExample: Notificationable {
// Минимальный кеш для хранения актуальных данных, чтобы не обращаться к БД
public static var alarmsCache: [String : TimerSound] = [:]
// Центр уведомлений
public static let notificationCenter = UNUserNotificationCenter.current()
public static func notificationRequest() {
// Вспомогательный метод для получения разрешения на работу с нотификациями
}
public static func checkUsersSettings(completion: @escaping (Bool) -> ()) {
// Вспомогательный метод для проверки разрешений
}
public static func scheduleNotification(alarm: Alarm, interval: TimeInterval) {
let content = UNMutableNotificationContent()
content.title = "Some Alarm"
content.body = "Timer fires"
content.badge = 1
let soundName = UNNotificationSoundName("\(alarm.sound.sound).mp3")
content.sound = UNNotificationSound(named: soundName)
alarmsCache[alarm.id] = alarm.sound
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: interval, repeats: false)
let identifier = alarm.id
let request = UNNotificationRequest(identifier: identifier, content: content, trigger: trigger)
notificationCenter.add(request) { (error) in
if let error = error {
// Выводим куда-то ошибки
}
}
}
public static func removeNotification(id: String) {
// Удаляем установленное уведомление (например, когда пользователь его отключил)
notificationCenter.removePendingNotificationRequests(withIdentifiers: [id])
}
public static func removeAllPendingNotifications() {
// Удаления всех уведомлений (например, когда приложение было открыто и можно использовать внутренние таймеры)
DispatchQueue.main.async {
notificationCenter.getPendingNotificationRequests { requestsArray in
requestsArray.forEach { removeNotification(id: $0.identifier ) }
}
}
}
public func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
// Запуск аудио сервиса для проигрывание звука
}
public func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
// Реализация перехода к нужному экрану
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment