Ios Swift 3-Firebase推送通知,我该怎么办?

Ios Swift 3-Firebase推送通知,我该怎么办?,ios,swift,firebase,swift3,firebase-notifications,Ios,Swift,Firebase,Swift3,Firebase Notifications,我确实喜欢下面的Swift 2。但它在Swift 3中不起作用。我怎样才能提供这个?如果有人能解释一下,那就太好了 使用选项完成启动 let notificationSettings = UIUserNotificationSettings(forTypes: [.Alert, .Badge, .Sound], categories: nil) UIApplication.sharedApplication().registerUserNotificationSettings(notificat

我确实喜欢下面的Swift 2。但它在Swift 3中不起作用。我怎样才能提供这个?如果有人能解释一下,那就太好了

使用选项完成启动

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

我可以做简单的本地通知,但不能从Firebase远程推送通知

我试过了


仍然不起作用。

AppDelegate方法名称发生了一些变化,并且引入了UserNotifications框架。在iOS 10及更高版本中,您必须使用此框架进行通知,因为其他方法正在被弃用

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

    ...
}

请务必记住,可能有不同的设备运行不同版本的iOS,并且它们可能具有不同的通知功能。我知道前面的答案确实指向了正确的方向

如果要接收实例通知或基于事件的通知,我们需要导入FirebaseInstanceID。这类通知类似于当有人转发我们的帖子、喜欢帖子或消息通知时弹出的通知

但是,如果有人正在查找进入
AppDelegate
中的
didfishlaunchingwithoptions
函数的完整代码,请查看:

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

这是我的工作代码8,Swift 3

在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]
以及需要接收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)

    }
}

委托方法的名称略有更改。通过键入每个方法的名称,您应该可以在Swift 3中看到相应的方法作为建议。
    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.")
}
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]
@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)

    }
}