在 Swift iOS 中推送通知



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

当应用程序打开时(即在前台(,我可以收到通知

,但当应用程序在后台或终止时,我无法收到通知。

以下是我的代码

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

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

  func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {    
        completionHandler([.alert, .badge, .sound])
}

谢谢。

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

{
  "to": "<REGISTRATION_TOKEN_HERE>",
  "notification": {
    "body": "Yipeee!!! I nailed it",
    "sound" : "default"
  },
  "data" : ""
}

我忘了添加这个方法

didReceiveRemoteNotification

相关内容

  • 没有找到相关文章

最新更新