Swift iOS中的推送通知

Swift iOS中的推送通知,ios,swift,firebase,firebase-cloud-messaging,firebase-notifications,Ios,Swift,Firebase,Firebase Cloud Messaging,Firebase Notifications,我正在使用iOS Swift通知模块。我没有收到设备上的警报/横幅通知 我能够在应用程序打开(即前台)时收到通知,但在应用程序处于后台或终止时无法收到通知 下面是我的代码 import UIKit import UserNotifications import Firebase @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate,

我正在使用iOS Swift通知模块。我没有收到设备上的警报/横幅通知

我能够在应用程序打开(即前台)时收到通知,但在应用程序处于后台或终止时无法收到通知

下面是我的代码

import UIKit

import UserNotifications

import Firebase

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate, FIRMessagingDelegate {

    var window: UIWindow?

    //  MARK: - Application Life Cycle
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.

        FIRApp.configure()

        askNotificationPermission(application)

        NotificationCenter.default.removeObserver(self, name: NSNotification.Name.firInstanceIDTokenRefresh, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(self.getFirebaseInstaceID(_:)), name: NSNotification.Name.firInstanceIDTokenRefresh, object: nil)

        connectToFcm()

        return true
    }

    // MARK:- Push Notification Delegate Methods
    @nonobjc func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        FIRInstanceID.instanceID().setAPNSToken(deviceToken, type: FIRInstanceIDAPNSTokenType.sandbox)
    }

    func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
        print(error)
    }

    func applicationReceivedRemoteMessage(_ remoteMessage: FIRMessagingRemoteMessage) {
        let appdata = remoteMessage.appData as NSDictionary as! [String: AnyObject]
        print(appdata)
    }

    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {
        print(userInfo)
    }

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

    // Receive displayed notifications for iOS 10 devices.
    @available(iOS 10.0, *)
    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {

        let userInfo = notification.request.content.userInfo
        print("Message ID: \(userInfo["gcm.message_id"]!)")
        print("%@", userInfo)
    }

    //  MARK: - Permissions
    func askNotificationPermission(_ application: UIApplication) {
        if #available(iOS 10.0, *) {

            let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
            UNUserNotificationCenter.current().requestAuthorization(options: authOptions, completionHandler: { (finished, error) in

            })

            UNUserNotificationCenter.current().delegate = self

            FIRMessaging.messaging().remoteMessageDelegate = self

        } else {

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

        application.registerForRemoteNotifications()
    }

    //  MARK: - Firebase Connection Methods
    @objc func getFirebaseInstaceID(_ notification: Notification) {

        if isNotNull(FIRInstanceID.instanceID().token() as AnyObject?) {
            let strFirebaseInstanceID = FIRInstanceID.instanceID().token()! as String
            if !strFirebaseInstanceID.isEmpty {
                print("Firebase Instance ID - \(strFirebaseInstanceID)")
                setString(strValue: strFirebaseInstanceID, forKey: Default.firebaseInstanceID)

                NotificationCenter.default.post(name: Notification.Name(rawValue: Notifications.nSendFirebaseID), object: nil)
            } else {
                setString(strValue: "", forKey: Default.firebaseInstanceID)
            }
        } else {
            setString(strValue: "", forKey: Default.firebaseInstanceID)
        }

        connectToFcm()
    }

    func connectToFcm() {
        FIRMessaging.messaging().connect { (error) in
            if (error != nil) {
                print("Unable to connect with FCM. \(error)")
            } else {
                print("Connected to FCM.")
            }
        }
    }
}

当您使用FCM发送推送时,请尝试将此有效负载发送到FCM进行推送

{
  "to": "<REGISTRATION_TOKEN_HERE>",
  "notification": {
    "body": "Yipeee!!! I nailed it",
    "sound" : "default"
  },
  "data" : ""
}
{
“致”:“,
“通知”:{
“身体”:“哎呀!!!我搞定了”,
“声音”:“默认值”
},
“数据”:”
}

当您使用FCM发送推送时,请尝试将此有效负载发送到FCM进行推送

{
  "to": "<REGISTRATION_TOKEN_HERE>",
  "notification": {
    "body": "Yipeee!!! I nailed it",
    "sound" : "default"
  },
  "data" : ""
}
{
“致”:“,
“通知”:{
“身体”:“哎呀!!!我搞定了”,
“声音”:“默认值”
},
“数据”:”
}

对于iOS 10.*,您需要在下面的
willPresent notification
方法列表的完成处理程序中提供push notification present选项。这样做可能会有帮助

  func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {    

        completionHandler([.alert, .badge, .sound])

}

谢谢。

对于iOS 10。*,您需要在下面的
willPresent notification
方法列表的完成处理程序中为推送通知提供选项。这样做可能会有帮助

  func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {    

        completionHandler([.alert, .badge, .sound])

}

谢谢。

我忘了添加此方法

didReceiveRemoteNotification

我忘了添加这个方法

didReceiveRemoteNotification


你能分享你发送的有效载荷吗?你面临的问题是什么操作系统?@Karthick我面临的问题是iOS 10.1刚刚在其中一个答案中看到你的评论。您可以发布一个使用通知控制台发送的示例消息的屏幕截图吗?(编辑敏感细节)亲爱的@VaibhavJhaveri,我们已将您的更改回滚到与社区编辑选择更同步的版本。如果您有任何疑问,我建议您重新阅读一般或特别的。你也可以在Meta上搜索,并最终在上提出问题。你能分享你发送的有效负载吗?你面临这个问题的操作系统是什么?@Karthick我在iOS 10上面临这个问题。1刚刚在其中一个答案中看到你的评论。您可以发布一个使用通知控制台发送的示例消息的屏幕截图吗?(编辑敏感细节)亲爱的@VaibhavJhaveri,我们已将您的更改回滚到与社区编辑选择更同步的版本。如果您有任何疑问,我建议您重新阅读一般或特别的。您也可以在Meta上搜索,并最终在上提出问题。我正在使用Firebase控制台发送通知我没有尝试使用控制台发送推送,但我使用googleapi的使用
post request
,url正在
https://gcm-http.googleapis.com/gcm/send
和标题
授权:key=yourKey内容类型:application/json
@TechGeek\u iOS
https://gcm-http.googleapis.com/gcm/send
是GCM端点。尽管两者仍然兼容,但对于FCM,请尽可能使用
https://fcm.googleapis.com/fcm/send
:)另外,我注意到您的格式--“to”:“FCM\u INSTANCE\u ID/GCM\u ID\u GOES\u HERE”。在那里包含
GCM\u ID
是没有意义的(我甚至不确定你所说的
GCM\u ID
是什么意思。FCM\u INSTANCE\u ID是filinstanceid.instanceID().token,为每个设备生成我正在使用Firebase控制台发送通知我没有尝试使用控制台发送推送,但我使用googleapi的post请求发送推送,url为
https://gcm-http.googleapis.com/gcm/send
和标题
授权:key=yourKey内容类型:application/json
@TechGeek\u iOS
https://gcm-http.googleapis.com/gcm/send
是GCM端点。尽管两者仍然兼容,但对于FCM,请尽可能使用
https://fcm.googleapis.com/fcm/send
:)另外,我注意到您的格式--“to”:“FCM\u INSTANCE\u ID/GCM\u ID\u GOES\u HERE”。在那里包含
GCM\u ID
是没有意义的(我甚至不知道你所说的
GCM\u ID
是什么意思。FCM\u实例ID是为每个设备生成的FIRInstanceID.instanceID().token。没有帮助尝试。没有帮助