Swift 3 - Firebase Push Notification, How can I do

2019-07-02 01:14发布

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.

3条回答
相关推荐>>
2楼-- · 2019-07-02 02:08

This is what works for me Xcode 8, Swift 3.

Inside didFinishLaunchingwithOptions func in AppDelegate.swift

if #available(iOS 10.0, *) {
            let authOptions : UNAuthorizationOptions = [.alert, .badge, .sound]
            UNUserNotificationCenter.current().requestAuthorization(
                options: authOptions,
                completionHandler: {granted, error in
                    print(granted)
            })

            // For iOS 10 display notification (sent via APNS)
            UNUserNotificationCenter.current().delegate = self
            // For iOS 10 data message (sent via FCM)
            FIRMessaging.messaging().remoteMessageDelegate = self

        } else {
            let settings: UIUserNotificationSettings =
                UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
            application.registerUserNotificationSettings(settings)
        }

        application.registerForRemoteNotifications()

        FIRApp.configure()

        // [START set_messaging_delegate]
        FIRMessaging.messaging().remoteMessageDelegate = self
        // [END set_messaging_delegate]

And the Delegates required to receive notifications from firebase:

@available(iOS 10, *)
extension AppDelegate : UNUserNotificationCenterDelegate {

    // Receive displayed notifications for iOS 10 devices.

    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        let userInfo = notification.request.content.userInfo
        // Print message ID.
        print("Message ID: \(userInfo["gcm.message_id"]!)")

        // Print full message.
        print("%@", userInfo)

        let aps = userInfo["aps"] as! [String: Any]
        let notificationMessage = aps["alert"] as! String // processed content from notificaton

    }

}

extension AppDelegate : FIRMessagingDelegate {
    // Receive data message on iOS 10 devices.
    func applicationReceivedRemoteMessage(_ remoteMessage: FIRMessagingRemoteMessage) {
        print("%@", remoteMessage.appData)

    }
}
查看更多
Juvenile、少年°
3楼-- · 2019-07-02 02:13

It is very important to remember that there may be different devices that run different versions of the iOS, and they may have different notification capabilities. I understand that the previous answer does point in the right direction.

We need to import FirebaseInstanceID, if we are to receive instance, or event based notifications. Such notifications are like the ones that pop-up when someone retweets our post, or likes a post, or a message notification.

However, if someone is looking for the complete code that goes into the didFinishLaunchingWithOptions function in AppDelegate, here it is:

    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {

    FIRApp.configure()

    if #available(iOS 10.0, *) {
        let authOptions : UNAuthorizationOptions = [.Alert, .Badge, .Sound]
           UNUserNotificationCenter.currentNotificationCenter().requestAuthorizationWithOptions(
            authOptions, completionHandler: {_,_ in })
    } else {
        // Fallback on earlier versions
        let settings: UIUserNotificationSettings =
            UIUserNotificationSettings(forTypes: [.Alert, .Badge, .Sound], categories: nil)
        application.registerUserNotificationSettings(settings)
        application.registerForRemoteNotifications()
    }

    application.registerForRemoteNotifications()

    // Add observer for InstanceID token refresh callback.
NSNotificationCenter.defaultCenter().addObserver(self,
    selector: #selector(self.tokenRefreshNotification),
    name: kFIRInstanceIDTokenRefreshNotification,
    object: nil)

    return true
}

  func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject],
               fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) {
// This is required if you are receiving a notification message while your app is in the background, which is the most common case!!

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

print("%@", userInfo)
}


func tokenRefreshNotification(notification: NSNotification) {
if let refreshedToken = FIRInstanceID.instanceID().token() {
  print("InstanceID token: \(refreshedToken)")
}

connectToFcm()
}


func connectToFcm() {
FIRMessaging.messaging().connectWithCompletion { (error) in
  if (error != nil) {
    print("Unable to connect with FCM. \(error)")
  } else {
    print("Connected to FCM.")
  }
 }
}
func applicationDidBecomeActive(application: UIApplication) {
connectToFcm()
}
func applicationDidEnterBackground(application: UIApplication) {
FIRMessaging.messaging().disconnect()
print("Disconnected from FCM.")
}
查看更多
孤傲高冷的网名
4楼-- · 2019-07-02 02:18

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)
    }

    ...
}

Registering for Push Notifications in Xcode 8/Swift 3.0?

查看更多
登录 后发表回答