当应用程序处于后台/关闭状态时,FCM通知无法唤醒

时间:2018-09-24 06:12:23

标签: ios swift firebase apple-push-notifications firebase-cloud-messaging

我尝试了许多解决方案,但是都没有用。当应用程序处于活动状态时,我能够收到FCM通知,但是当应用程序处于后台或终止状态时,我不会收到通知。从过去2天开始尝试。但没有运气。

1。启用的远程通知

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

var window: UIWindow?
let userDefaults = UserDefaultsData()
var notificationsDB: Tbl_Notifications?

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

    DBFileURL.copyFile(fileName: "nActivity.sqlite")

    IQKeyboardManager.shared.enable = true

    let savedData = userDefaults.findBool(key: Keys.UserDefaultsKey.IS_LOGGED_IN)

    if(savedData){
        let mainStoryboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
        let dashboardViewController = mainStoryboard.instantiateViewController(withIdentifier: "dashboard") as!
        DashboardTabBarController
        window!.rootViewController = dashboardViewController
    }

    UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { (isGranted, err) in
        if err != nil {
            //Something bad happend
        } else {
            UNUserNotificationCenter.current().delegate = self
            Messaging.messaging().delegate = self

            DispatchQueue.main.async {
                UIApplication.shared.registerForRemoteNotifications()
            }
        }
    }

    FirebaseApp.configure()

    return true
}


func applicationWillResignActive(_ application: UIApplication) {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}

func applicationDidEnterBackground(_ application: UIApplication) {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    Messaging.messaging().shouldEstablishDirectChannel = false
}

func applicationWillEnterForeground(_ application: UIApplication) {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}

func applicationDidBecomeActive(_ application: UIApplication) {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    ConnectToFCM()
}


func applicationWillTerminate(_ application: UIApplication) {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

func ConnectToFCM() {
    Messaging.messaging().shouldEstablishDirectChannel = true

    if let token = InstanceID.instanceID().token() {
        print("DCS: " + token)
    }

}

func messaging(_ messaging: Messaging, didRefreshRegistrationToken fcmToken: String) {
    ConnectToFCM()
}

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

func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {

}

func application(application: UIApplication, didRegisterUserNotificationSettings notificationSettings: UIUserNotificationSettings)
{
    application.registerForRemoteNotifications()
}

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

func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) {
    print("Firebase registration token: \(fcmToken)")

    let dataDict:[String: String] = ["token": fcmToken]
    NotificationCenter.default.post(name: Notification.Name("FCMToken"), object: nil, userInfo: dataDict)

    if fcmToken != "" {
        userDefaults.save(key: "fcmToken", value: fcmToken)
    }
}

func messaging(_ messaging: Messaging, didReceive remoteMessage: MessagingRemoteMessage) {

    print("backend data", remoteMessage.appData)
    UIApplication.shared.applicationIconBadgeNumber = UIApplication.shared.applicationIconBadgeNumber + 1

    let token = userDefaults.findString(key: "token")
    if token != "" {
        let notification: String = remoteMessage.appData[AnyHashable("notification")]! as! String

        if let notificationData = notification.data(using: .utf8) {
            do {
                let dataDictonary: NSDictionary = try JSONSerialization.jsonObject(with: notificationData, options: .allowFragments) as! NSDictionary

                populateNotificationJSON(dataDictonary: dataDictonary)
            } catch {
                print(error.localizedDescription)
            }
        }
    }
}

func populateNotificationJSON(dataDictonary: NSDictionary) {
    let commonParserInstance = CommonParser()

    let activityId: String = commonParserInstance.parse(dictionary: dataDictonary, key: "activityId", exceptionString: "")
    if activityId != "" {
        let message: String = commonParserInstance.parse(dictionary: dataDictonary, key: "message", exceptionString: "N/A")
        let time = getTime()

        notificationsDB = Tbl_Notifications()
        notificationsDB?.activityId = activityId
        notificationsDB?.message = message
        notificationsDB?.time = time

        let notificationModelDB = NotificationsDBModel.getInstance()
        notificationModelDB.open()

        let isInserted = notificationModelDB.retriveData(activityId: activityId)
        if isInserted {
            notificationModelDB.updateData(tbl_Notifications: notificationsDB!)
        } else {
            notificationModelDB.insertData(notificationsDB!)
        }

        notificationModelDB.close()

        showNotification(message: message)
    }
}

func showNotification(message: String) {

    let center = UNUserNotificationCenter.current()
    let content = UNMutableNotificationContent()
    content.body = message
    content.sound = UNNotificationSound.default()

    //Time interval: Schedule a notification for a number of seconds later. For example to trigger in 1 seconds:
    let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 1, repeats: false)

    let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: trigger)
    center.add(request)
}

func getTime() -> String {

    let formatter = DateFormatter()
    formatter.locale = Locale(identifier: "en_US_POSIX")
    formatter.dateFormat = "MMMM dd yyyy h:mm a "
    formatter.amSymbol = "AM"
    formatter.pmSymbol = "PM"

    let dateString = formatter.string(from: Date())

    return dateString
}
}

以下是有效载荷

[
  AnyHashable("from"): 425251449625, 
 AnyHashable("notification"): 
{
 "activityId":122,
 "activityNo":"122",
 "message":"The Activity No:122 is assigned by balaram balaram"
},
AnyHashable("content_available"): true, 
AnyHashable("mutable_content"): true, 
AnyHashable("priority"): high
]

请帮助我所缺少的吗?

0 个答案:

没有答案