tobeiosdev tobeiosdev - 2 months ago 130
Swift Question

Swift 3 - Firebase Push Notification, How can I do?

I do like below in Swift 2. But It's not working in Swift 3. How Can I provide this? If someone explain this It would be great.

didFinishLaunchingWithOptions

let notificationSettings = UIUserNotificationSettings(forTypes: [.Alert, .Badge, .Sound], categories: nil)
UIApplication.sharedApplication().registerUserNotificationSettings(notificationSettings)
application.registerForRemoteNotifications()


and

func application(application: UIApplication, didRegisterUserNotificationSettings notificationSettings: UIUserNotificationSettings) {
if notificationSettings.types != .None {
application.registerForRemoteNotifications()
}
}

func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {

print("Meesage ID \(userInfo["gcm_message_id"]!)")
print(userInfo)

}


I can do simple local notification but, I couldn't remote push notification from Firebase.


I tried


UNUserNotificationCenter.currentNotificationCenter().delegate = self

UNUserNotificationCenter.currentNotificationCenter().requestAuthorizationWithOptions([.Alert, .Badge, .Sound]) { (success, error:NSError?) in

if success {
print("Notification access true!")
application.registerForRemoteNotifications()
}
else {
print(error?.localizedDescription)
}

}


and

func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {

print("Meesage ID \(userInfo["gcm_message_id"]!)")
print(userInfo)

}


still doesn't work.

Answer

The AppDelegate method names have changed a little and UserNotifications framework has been introduced. You must use this framework for notifications in iOS 10 and above as the other methods are being deprecated.

import UserNotifications

...

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    ...

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

        UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { (granted, error) in
            // Enable or disable features based on authorization.
        }

        application.registerForRemoteNotifications()

        return true
    }

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

        print("Message ID \(userInfo["gcm.message_id"]!)")
        print(userInfo)
    }

    ...
}

http://stackoverflow.com/questions/37956482/registering-for-push-notifications-in-xcode-8-swift-3-0

Comments