Guest User

Untitled

a guest
Mar 17th, 2018
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.97 KB | None | 0 0
  1. import UIKit
  2. import UserNotifications
  3.  
  4. protocol PushManagerDelegate {
  5. func pushManagerUpdated()
  6. }
  7.  
  8. class PushManager: NSObject {
  9. static let sharedInstance = PushManager()
  10.  
  11. var deviceToken:Data?
  12. var delegate: PushManagerDelegate?
  13.  
  14. func registerForPushNotifications() {
  15.  
  16. UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { (permissionGranted, error) in
  17. DispatchQueue.main.async {
  18. print("registerForPushNotifications(): permissionGranted? \(permissionGranted)")
  19.  
  20. guard permissionGranted else {
  21. return
  22. }
  23. self.getNotificationSettings()
  24. }
  25. }
  26.  
  27. }
  28.  
  29. func didRegisterForRemoteNotifications(deviceToken: Data) {
  30. self.deviceToken = deviceToken
  31.  
  32. print("Device Token: \(deviceToken.deviceTokenString())")
  33.  
  34. delegate?.pushManagerUpdated()
  35. }
  36.  
  37. func getNotificationSettings() {
  38. UNUserNotificationCenter.current().getNotificationSettings { (settings) in
  39. DispatchQueue.main.async {
  40. print("Notification settings: \(settings)")
  41.  
  42. guard settings.authorizationStatus == .authorized else { return }
  43. UIApplication.shared.registerForRemoteNotifications()
  44. }
  45. }
  46. }
  47. }
  48.  
  49. extension PushManager: UNUserNotificationCenterDelegate {
  50.  
  51. func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
  52.  
  53. //Tell iOS to still show the push notification so it's not just consumed in the foreground
  54. completionHandler(UNNotificationPresentationOptions.alert)
  55. }
  56. }
  57.  
  58. extension Data {
  59. func deviceTokenString() -> String {
  60. let tokenParts = self.map { data -> String in
  61. return String(format: "%02.2hhx", data)
  62. }
  63.  
  64. return tokenParts.joined()
  65. }
  66. }
Add Comment
Please, Sign In to add comment