metatext-app-ios-iphone-ipad/Services/UserNotificationService.swift

70 lines
2.3 KiB
Swift
Raw Normal View History

2020-08-12 09:24:39 +02:00
// Copyright © 2020 Metabolist. All rights reserved.
import Foundation
import Combine
import UserNotifications
class UserNotificationService: NSObject {
2020-08-12 09:24:39 +02:00
private let userNotificationCenter: UNUserNotificationCenter
init(userNotificationCenter: UNUserNotificationCenter = .current()) {
self.userNotificationCenter = userNotificationCenter
super.init()
userNotificationCenter.delegate = self
2020-08-12 09:24:39 +02:00
}
}
extension UserNotificationService {
2020-08-12 09:24:39 +02:00
func isAuthorized() -> AnyPublisher<Bool, Error> {
getNotificationSettings()
.map(\.authorizationStatus)
.flatMap { [weak self] status -> AnyPublisher<Bool, Error> in
2020-08-12 09:24:39 +02:00
if status == .notDetermined {
return self?.requestProvisionalAuthorization()
.eraseToAnyPublisher()
?? Empty().eraseToAnyPublisher()
2020-08-12 09:24:39 +02:00
}
return Just(status == .authorized || status == .provisional)
.setFailureType(to: Error.self)
.eraseToAnyPublisher()
}
.eraseToAnyPublisher()
}
}
private extension UserNotificationService {
2020-08-12 09:24:39 +02:00
func getNotificationSettings() -> AnyPublisher<UNNotificationSettings, Never> {
Future<UNNotificationSettings, Never> { [weak self] promise in
self?.userNotificationCenter.getNotificationSettings { promise(.success($0)) }
2020-08-12 09:24:39 +02:00
}
.eraseToAnyPublisher()
}
func requestProvisionalAuthorization() -> AnyPublisher<Bool, Error> {
Future<Bool, Error> { [weak self] promise in
self?.userNotificationCenter.requestAuthorization(
2020-08-12 09:24:39 +02:00
options: [.alert, .sound, .badge, .provisional]) { granted, error in
if let error = error {
return promise(.failure(error))
}
return promise(.success(granted))
}
}
.eraseToAnyPublisher()
}
}
extension UserNotificationService: UNUserNotificationCenterDelegate {
func userNotificationCenter(
_ center: UNUserNotificationCenter,
willPresent notification: UNNotification,
withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
print(notification.request.content.body)
completionHandler(.banner)
}
}