推送通知不在前台工作

时间:2017-11-16 07:51:23

标签: ios swift firebase push-notification unusernotificationcenter

当我的应用程序运行时,我从firebase发送了通知,调用了UNUserNotification委托方法,我收到了通知,它显示在顶部,但是当我从我的API服务器发送通知时,

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

firebase委托正在调用,我可以获取数据,但通知没有显示在顶部。

我的代码如下:

func registerForPushNotification(_ application: UIApplication)
{

    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 })
        // For iOS 10 data message (sent via FCM
        //Messaging.messaging().delegate = self
    } else {
        let settings: UIUserNotificationSettings =
            UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)

        application.registerUserNotificationSettings(settings)
    }
    application.registerForRemoteNotifications()
    application.applicationIconBadgeNumber = 0

}

func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data)
{
    print("device token %@",deviceToken)

    var deviceTokenString = String(format: "%@", deviceToken as CVarArg)
    deviceTokenString = deviceTokenString.trimmingCharacters(in: CharacterSet(charactersIn: "<>"))
    deviceTokenString = deviceTokenString.replacingOccurrences(of: " ", with: "")

    print(deviceTokenString)
    //saveDeviceIdinDefaults(deviceId: deviceTokenString)
    Messaging.messaging().apnsToken = deviceToken

//        InstanceID.instanceID().setAPNSToken(deviceToken, type:InstanceIDAPNSTokenType.sandbox)
//        InstanceID.instanceID().setAPNSToken(deviceToken, type:InstanceIDAPNSTokenType.prod)

}

// The callback to handle data message received via FCM for devices running iOS 10 or above.
func application(received remoteMessage: MessagingRemoteMessage) {
    print(remoteMessage.appData)

}

@available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
    print("Userinfo \(response.notification.request.content.userInfo)")

    if response.actionIdentifier == UNNotificationDismissActionIdentifier {
        print ("Message Closed")
    }
    else if response.actionIdentifier == UNNotificationDefaultActionIdentifier {
        print ("App is Open")
    }

    // Else handle any custom actions. . .
    completionHandler()


    //    print("Userinfo \(response.notification.request.content.userInfo)")
}

func application(_ application: UIApplication,
                 didFailToRegisterForRemoteNotificationsWithError error: Error) {
    print("Failed to register: \(error)")
}

@objc func tokenRefreshNotification(_ notification: NSNotification) {
    //  print("refresh token call")
    guard let contents = InstanceID.instanceID().token()
        else {
            return
    }
    // let refreshedToken = FIRInstanceID.instanceID().token()!
    let refreshedToken = contents//InstanceID.instanceID().token()
    print("InstanceID token: \(refreshedToken)")

    Constant.saveFcmToken(fcmToken: refreshedToken, key: "deviceid")
    //        UserDefaults.standard.set(refreshedToken, forKey: "deviceid")

    print("InstanceID token: \(contents)")
    connectToFcm()
}

func connectToFcm() {
    // Won't connect since there is no token
    guard InstanceID.instanceID().token() != nil else {
        print("FCM: Token does not exist.")
        return
    }

    // Disconnect previous FCM connection if it exists.
    Messaging.messaging().disconnect()

    Messaging.messaging().connect { (error) in
        if error != nil {
            print("FCM: Unable to connect with FCM. \(error.debugDescription)")
        } else {
            print("Connected to FCM.")
        }
    }
}
// [START refresh_token]

//MARK: FCM Token Refreshed
func messaging(_ messaging: Messaging, didRefreshRegistrationToken fcmToken: String) {
    // FCM token updated, update it on Backend Server
    print("Firebase registration token: \(fcmToken)")
    saveDeviceIdinDefaults(deviceId: fcmToken)
}


func messaging(_ messaging: Messaging, didReceive remoteMessage: MessagingRemoteMessage) {
    print("remoteMessage: \(remoteMessage)")
    UNUserNotificationCenter.current().requestAuthorization(
        options: [.alert,.sound,.badge],
        completionHandler: { (granted,error) in
            NotificationCenter.default.post(name: NSNotification.Name("GetPollsUpdateNotification"), object: nil)
            //self.isGrantedNotificationAccess(data: remoteMessage.appData)
    }
    )

    //            let notifiDict = remoteMessage.appData as! [String:String]
    //            print(notifiDict)
    //            let title = notifiDict["title"]
    //            let message = notifiDict["message"]
    //            let image = notifiDict["image"]
}

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

func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any]) {
    print(userInfo)
    if application.applicationState == .active {

        //write your code here when app is in foreground
    } else {
        //write your code here for other state
    }
}

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

    completionHandler([UNNotificationPresentationOptions.alert])

    let userInfo = notification.request.content.userInfo as! NSDictionary
    print("\(String(describing: userInfo))")

    print(notification.description)
}

有人可以帮助我吗?

1 个答案:

答案 0 :(得分:0)

我认为处理此问题的方法是使用以下委托方法:

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

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

    }

希望这有帮助。