使用Firebase API的推送通知在后台状态下无法正常工作

时间:2019-04-03 11:36:24

标签: swift firebase push-notification

我已经配置了firebase api以在iOS中获取推送通知。它在前景中工作,但在背景状态下无法正常工作。我不想习惯通知标签,因为它在android中不会处于终止状态。

我还需要在后台获取它,以便向服务器确认。

1 个答案:

答案 0 :(得分:0)

Iam using this :-
import UserNotifications
import Firebase
import FirebaseInstanceID
import FirebaseMessaging
 func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

        FirebaseApp.configure()
        Messaging.messaging().shouldEstablishDirectChannel = true
        Messaging.messaging().delegate = self
         if #available(iOS 10.0, *) {
            // For iOS 10 display notification (sent via APNS)
            UNUserNotificationCenter.current().delegate = self

            let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
            UNUserNotificationCenter.current().requestAuthorization(
                options: authOptions,
                completionHandler: {_, _ in })
        } else {
            let settings: UIUserNotificationSettings =
                UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
            application.registerUserNotificationSettings(settings)
        }
        application.beginBackgroundTask(withName: "showNotification", expirationHandler: nil)
        application.registerForRemoteNotifications()

        return true
    }
  func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) {
        print("Firebase registration token: \(fcmToken)")
        let token = Messaging.messaging().fcmToken
        print("FCM token: \(token ?? "")")
        Constants.kUserDefaults.set(token, forKey: appConstants.fcmToken)

    }
    func applicationReceivedRemoteMessage(_ remoteMessage: MessagingRemoteMessage) {
        print("Received data message: \(remoteMessage.appData)")
    }
    func application(_ application: UIApplication,
                     didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {

        InstanceID.instanceID().instanceID { (result, error) in
            if let error = error {
                print("Error fetching remote instange ID: \(error)")
            } else if let result = result {
                print("Remote instance ID token: \(result.token)")
                Constants.kUserDefaults.set(result.token, forKey: appConstants.fcmToken)
            }
        }
        Messaging.messaging().apnsToken = deviceToken as Data


    }
    private func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void)
    {
        completionHandler([UNNotificationPresentationOptions.alert,UNNotificationPresentationOptions.sound,UNNotificationPresentationOptions.badge])
    }
    func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
        print("Failed to register for remote notifications with error: \(error)")
    }

    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
        switch application.applicationState {
        case .inactive:
            print("Inactive")
            //Show the view with the content of the push
            completionHandler(.newData)

        case .background:
            print("Background")
            //Refresh the local model
            completionHandler(.newData)

        case .active:
            print("Active")
            completionHandler(UIBackgroundFetchResult.newData)
        }
        print(userInfo)

        guard let data: [String: Any] = userInfo as? [String: Any] else {
            return
        }
        print(data)
         let aps = data["aps"] as! NSDictionary
        let contentDict = aps["alert"] as! NSDictionary
         print(contentDict)
        let body = contentDict["body"] as! String
        let titleData = contentDict["title"] as! String
        print(titleData)
        createNotification(title: titleData, body: body)

        completionHandler(.newData)
    }

    func application(_ application: UIApplication, didRegister notificationSettings: UIUserNotificationSettings) {
        application.registerForRemoteNotifications()
    }
    @available(iOS 10.0, *)
    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response:UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void)
    {
        print("Handle push from background or closed")
        // if you set a member variable in didReceiveRemoteNotification, you will know if this is from closed or background
        print("\(response.notification.request.content.userInfo)")
    }

    func messaging(_ messaging: Messaging, didReceive remoteMessage: MessagingRemoteMessage) {
        print("Received data message: \(remoteMessage.appData)")
        guard let data: [String: Any] = remoteMessage.appData as? [String: Any] else {
            return
        }
// Handle Notification data
        let contentDict = data["alert"] as! NSDictionary
        print(contentDict)
        let body = contentDict["body"] as! String
        let titleData = contentDict["title"] as! String
        print(titleData)
        createNotification(title: titleData, body: body)

    }

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

        completionHandler([.alert, .badge, .sound])
    }
    func createNotification(title: String, body: String) {
        let content = UNMutableNotificationContent()
        content.title = NSString.localizedUserNotificationString(forKey: title, arguments: nil)
        content.body = NSString.localizedUserNotificationString(forKey: body, arguments: nil)
        //  content.title = "RedIron"
        // content.body = "Confirm"
        content.sound = UNNotificationSound.default()
        content.badge = NSNumber(integerLiteral: UIApplication.shared.applicationIconBadgeNumber + 1)

        let request = UNNotificationRequest.init(identifier: "pushNotif", content: content, trigger: nil)

        let center = UNUserNotificationCenter.current()
        center.add(request)
    }
   func applicationDidBecomeActive(_ application: UIApplication) {
       UIApplication.shared.applicationIconBadgeNumber = 0

    }
// and make sure on backend they have also set
content_available : true
priority : high
// on your project, In capabilities > background mode switch on > click on remote notifications and background fetch.
// its Works for me