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