Last active
April 20, 2021 03:15
-
-
Save dlsolution/7f9fbd3ac0ac447ee2d7cc649d04dec3 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// https://medium.com/@samermurad555/ios-provisional-notifications-eeb3832836fc | |
import UserNotifications | |
import UIKit | |
typealias GrantCb = (_ didGrant: Bool) -> Void | |
// Manages Notifications Permissions | |
class NotificationManager { | |
static let instance = NotificationManager() | |
private init() {} | |
func requestAccess(options: UNAuthorizationOptions, cb: GrantCb?) { | |
let center = UNUserNotificationCenter.current() | |
// make sure to run on main thread | |
DispatchQueue.main.async { | |
center.requestAuthorization(options: options) { (didGrant, error) in | |
if error != nil { | |
print("An error occurred", error ?? "no error") | |
cb?(false) | |
} else { | |
cb?(true) | |
} | |
} | |
} | |
} | |
// asking for provisional access by adding the .provisional option | |
func provisionalAccess(_ cb: GrantCb?) { | |
self.requestAccess(options: [.alert, .sound, .badge, .provisional], | |
cb: cb) | |
} | |
// Explicit access (prompts user for permissions) | |
func explicitAccess(_ cb: GrantCb?) { | |
self.requestAccess(options: [.alert, .sound, .badge], | |
cb: cb) | |
} | |
func loacalNotification(message: String, | |
after: TimeInterval = 5, | |
handler: ((_ error: Error?) -> Void)? = nil) { | |
self.provisionalAccess { (didGrant) in | |
if didGrant { | |
DispatchQueue.main.async { | |
let notifId = UUID().uuidString | |
let content = UNMutableNotificationContent() | |
content.body = message | |
content.title = "Quick message" | |
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: after, repeats: false) | |
let req = UNNotificationRequest(identifier: notifId, content: content, trigger: trigger) | |
let center = UNUserNotificationCenter.current() | |
center.add(req, withCompletionHandler: handler) | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment