Skip to content

Instantly share code, notes, and snippets.

@welbesw
Created March 7, 2018 23:56
Show Gist options
  • Save welbesw/7fa0537c0eac27ca47f31dc205e95742 to your computer and use it in GitHub Desktop.
Save welbesw/7fa0537c0eac27ca47f31dc205e95742 to your computer and use it in GitHub Desktop.
A simple push notification manager.
import UIKit
import UserNotifications
protocol PushManagerDelegate {
func pushManagerUpdated()
}
class PushManager: NSObject {
static let sharedInstance = PushManager()
var deviceToken:Data?
var delegate: PushManagerDelegate?
func registerForPushNotifications() {
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { (permissionGranted, error) in
DispatchQueue.main.async {
print("registerForPushNotifications(): permissionGranted? \(permissionGranted)")
guard permissionGranted else {
return
}
self.getNotificationSettings()
}
}
}
func didRegisterForRemoteNotifications(deviceToken: Data) {
self.deviceToken = deviceToken
print("Device Token: \(deviceToken.deviceTokenString())")
delegate?.pushManagerUpdated()
}
func getNotificationSettings() {
UNUserNotificationCenter.current().getNotificationSettings { (settings) in
DispatchQueue.main.async {
print("Notification settings: \(settings)")
guard settings.authorizationStatus == .authorized else { return }
UIApplication.shared.registerForRemoteNotifications()
}
}
}
}
extension PushManager: UNUserNotificationCenterDelegate {
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
//Tell iOS to still show the push notification so it's not just consumed in the foreground
completionHandler(UNNotificationPresentationOptions.alert)
}
}
extension Data {
func deviceTokenString() -> String {
let tokenParts = self.map { data -> String in
return String(format: "%02.2hhx", data)
}
return tokenParts.joined()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment