How to register push notifications in Swift 3?

1

Push notifications in versions prior to Xcode8, worked correctly, but when you migrate to swift 3, you no longer register the Token. My code is as follows:

application.registerUserNotificationSettings(UIUserNotificationSettings(types: [.badge, .sound, .alert], categories: nil));
            application.registerForRemoteNotifications()

How to register push notifications in Swift 3?

    
asked by Jhonattan 27.10.2016 в 16:34
source

1 answer

2

You have to import the framework UserNotifications and add the delegate UNUserNotificationCenterDelegate in the file AppDelegate.swift

Request permission from the user

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
}

Get the Token

func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {

    let deviceTokenString = deviceToken.reduce("", {$0 + String(format: "%02X", $1)})
    print(deviceTokenString)
}
    
answered by 27.10.2016 / 16:40
source