Last active
February 24, 2017 23:00
-
-
Save roymckenzie/dedd9c79aa55629c13e06165303b4130 to your computer and use it in GitHub Desktop.
Easily request permissions in iOS 9 and iOS 10
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
import UIKit | |
import UserNotifications | |
import PropellerPromise | |
struct NotificationPermissionController { | |
static var permissionsEnabled: Bool { | |
guard let settings = UIApplication.shared.currentUserNotificationSettings else { | |
return false | |
} | |
return settings.types.contains([.badge, .alert]) | |
} | |
static func requestPermission() -> Promise<Bool> { | |
let promise = Promise<Bool>() | |
if #available(iOS 10.0, *) { | |
UNUserNotificationCenter | |
.current() | |
.requestAuthorization(options: [.badge, .alert]) { success, error in | |
if let error = error { | |
promise.reject(error) | |
return | |
} | |
promise.fulfill(success) | |
if success { | |
registerForRemoteNotifications() | |
} | |
} | |
} else { | |
let settings = UIUserNotificationSettings(types: [.alert, .badge], categories: nil) | |
UIApplication.shared.registerUserNotificationSettings(settings) | |
NotificationCenter | |
.default | |
.addObserver(forName: .RemoteNotificationsRegistered, | |
object: nil, | |
queue: nil) { notification in | |
guard let success = notification.object as? Bool else { return } | |
promise.fulfill(success) | |
if success { | |
registerForRemoteNotifications() | |
} | |
} | |
} | |
return promise | |
} | |
static func registerForRemoteNotifications() { | |
UIApplication.shared.registerForRemoteNotifications() | |
} | |
} | |
extension NSNotification.Name { | |
static let RemoteNotificationsRegistered = NSNotification.Name(rawValue: "RemoteNotificationsRegistered") | |
} | |
extension AppDelegate { | |
func application(_ application: UIApplication, didRegister notificationSettings: UIUserNotificationSettings) { | |
guard let settings = application.currentUserNotificationSettings else { return } | |
let success = settings.types.contains([.badge, .alert]) | |
NotificationCenter | |
.default | |
.post(name: .RemoteNotificationsRegistered, | |
object: success) | |
} | |
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) { | |
let token = deviceToken.apnsTokenString() | |
// TODO:- Send token to server | |
} | |
} | |
//MARK: - APNS Token extension - | |
private extension Data { | |
func apnsTokenString() -> String { | |
return map { String(format: "%02.2hhx", arguments: [$0]) }.joined() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment