ios - 推送通知在前台不起作用

标签 ios swift firebase push-notification unusernotificationcenter

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

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

firebase 委托(delegate)正在调用,我可以获取数据,但通知未显示在顶部。

我的代码如下:

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

有人能帮帮我吗?

最佳答案

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

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

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

    }

希望这对您有所帮助。

关于ios - 推送通知在前台不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47324244/

相关文章:

javascript - Firebase 函数 setInterval 和 clearInterval 分别调用

ios - 应用程序启动图像未更新

ios - 应用程序被 Appstore 拒绝 - 带有问题 PLA 2.3 的 iOS

ViewController 扩展中的 Swift @IBActions

node.js - 对 nodejs 应用程序使用 firebase 身份验证

javascript - Firebase Passwordless Auth 在点击链接时显示网站未找到页面

ios Responder chain - View 如何捕获事件?

ios - 如何在 ios 中从一个 View 导航到另一个 View ?

swift - 我的捕获不适用于 url 请求

ios - 如何根据使用 RXSwift 的验证更改 UIButton 的 isEnabled 和 alpha 属性?