Registering for Push Notifications in Xcode 8/Swift 3.0? Registering for Push Notifications in Xcode 8/Swift 3.0? ios ios

Registering for Push Notifications in Xcode 8/Swift 3.0?


Import the UserNotifications framework and add the UNUserNotificationCenterDelegate in AppDelegate.swift

Request user permission

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {        let center = UNUserNotificationCenter.current()        center.requestAuthorization(options:[.badge, .alert, .sound]) { (granted, error) in            // Enable or disable features based on authorization.        }        application.registerForRemoteNotifications()        return true}

Getting device token

func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {    let deviceTokenString = deviceToken.reduce("", {$0 + String(format: "%02X", $1)})    print(deviceTokenString)}

In case of error

func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {        print("i am not available in simulator \(error)")}

In case if you need to know the permissions granted

UNUserNotificationCenter.current().getNotificationSettings(){ (settings) in            switch settings.soundSetting{            case .enabled:                print("enabled sound setting")            case .disabled:                print("setting has been disabled")            case .notSupported:                print("something vital went wrong here")            }        }


func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {    if #available(iOS 10, *) {        //Notifications get posted to the function (delegate):  func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: () -> Void)"        UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { (granted, error) in            guard error == nil else {                //Display Error.. Handle Error.. etc..                return            }            if granted {                //Do stuff here..                //Register for RemoteNotifications. Your Remote Notifications can display alerts now :)                DispatchQueue.main.async {                    application.registerForRemoteNotifications()                }            }            else {                //Handle user denying permissions..            }        }        //Register for remote notifications.. If permission above is NOT granted, all notifications are delivered silently to AppDelegate.        application.registerForRemoteNotifications()    }    else {        let settings = UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)        application.registerUserNotificationSettings(settings)        application.registerForRemoteNotifications()    }    return true}


import UserNotifications  

Next, go to the project editor for your target, and in the General tab, look for the Linked Frameworks and Libraries section.

Click + and select UserNotifications.framework:

// iOS 12 supportif #available(iOS 12, *) {      UNUserNotificationCenter.current().requestAuthorization(options:[.badge, .alert, .sound, .provisional, .providesAppNotificationSettings, .criticalAlert]){ (granted, error) in }    application.registerForRemoteNotifications()}// iOS 10 supportif #available(iOS 10, *) {      UNUserNotificationCenter.current().requestAuthorization(options:[.badge, .alert, .sound]){ (granted, error) in }    application.registerForRemoteNotifications()}// iOS 9 supportelse if #available(iOS 9, *) {      UIApplication.shared.registerUserNotificationSettings(UIUserNotificationSettings(types: [.badge, .sound, .alert], categories: nil))    UIApplication.shared.registerForRemoteNotifications()}// iOS 8 supportelse if #available(iOS 8, *) {      UIApplication.shared.registerUserNotificationSettings(UIUserNotificationSettings(types: [.badge, .sound, .alert], categories: nil))    UIApplication.shared.registerForRemoteNotifications()}// iOS 7 supportelse {      application.registerForRemoteNotifications(matching: [.badge, .sound, .alert])}

Use Notification delegate methods

// Called when APNs has assigned the device a unique tokenfunc application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {      // Convert token to string    let deviceTokenString = deviceToken.reduce("", {$0 + String(format: "%02X", $1)})    print("APNs device token: \(deviceTokenString)")}// Called when APNs failed to register the device for push notificationsfunc application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {      // Print the error to console (you should alert the user that registration failed)    print("APNs registration failed: \(error)")}

For receiving push notification

func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {    completionHandler(UIBackgroundFetchResult.noData)}

Setting up push notifications is enabling the feature within Xcode 8for your app. Simply go to the project editor for your target and thenclick on the Capabilities tab. Look for Push Notifications and toggleits value to ON.

Check below link for more Notification delegate methods

Handling Local and Remote Notifications UIApplicationDelegate - Handling Local and Remote Notifications

https://developer.apple.com/reference/uikit/uiapplicationdelegate