【问题标题】:Push notification is not receiving in iOS swift?iOS swift中没有收到推送通知?
【发布时间】:2018-05-05 11:31:51
【问题描述】:

我正在使用FCM 进行推送通知。 FCM 已连接,设备注册成功,我可以打印设备令牌,但设备没有收到通知。 一般 -> 功能选项卡 -> 在后台模式下启用推送通知和远程通知。

在这里注册设备以进行远程通知。

  func application(
    _ application: UIApplication,
    didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data
    ) {

    let trimEnds:String! = {
        deviceToken.description.trimmingCharacters(
            in: CharacterSet(charactersIn: "<>"))
    }()


    let cleanToken:String! = {
        trimEnds.replacingOccurrences(of: " ", with: "")
    }()

    let token = deviceToken.map { String(format: "%02.2hhx", $0) }.joined()
    print(token)

    UserDefaults.standard.set(token, forKey: "deviceToken")
    UserDefaults.standard.synchronize()

    #if DEBUG
    //For Firebase
    FIRInstanceID.instanceID().setAPNSToken(deviceToken, type: FIRInstanceIDAPNSTokenType.sandbox)
    #else
    FIRInstanceID.instanceID().setAPNSToken(deviceToken, type: FIRInstanceIDAPNSTokenType.prod)
    #endif

    print("Device Token:", token)


}

这里我调用didReceiveRemoteNotification方法在注册设备上接收通知:

   func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {
    print("-=-=-=-=-\nDid receive notification\n-=-=-=-",userInfo)
    print("-=-=-=-=-\n")

       NotificationCenter.default.post(name: Notification.Name(rawValue: "notification_recieved"), object: nil)

    if userInfo.index(forKey: "chat_id") != nil {
        print("messag push")
        if (AppUtility?.hasValidText(User.userID))! {
            //let friendImage = userInfo["path"] as! String
            let chatID = userInfo["chat_id"] as! String
            let friendId = userInfo["to"] as! String
            let unRead = userInfo["unread"] as! String
            print(unRead)
            UnReadMsgs = unRead

            let dictAPS = userInfo["aps"] as! NSDictionary
            let dict = dictAPS["alert"] as! NSDictionary
            let friendName = dict["title"] as! String
            let friendMsg = dict["body"] as! String

            if(UIApplication.shared.applicationState == UIApplicationState.active){

                print("app is Active")
                if let wd = self.window {
                    var VC = wd.rootViewController
                    if(VC is UINavigationController){
                        VC = (VC as! UINavigationController).visibleViewController
                        if(VC is ChatViewController!){
                            print("Chat Screen")
                            let chatVC : ChatViewController = VC as! ChatViewController
                            if chatVC.chatId == chatID{
                                print("Same Chat")
                                self.clearChatWithChatID(chatID)
                            }else{
                                CustomNotificationView.showNotificationPopUp(self.window!, name: friendName, msg: friendMsg, image: "", chat: chatID, friendID: friendId)

                                playSound()
                                print("Other Chat")
                            }
                        }else{
                            let nc = NotificationCenter.default
                            nc.post(name: Notification.Name(rawValue: "MessageGet"),
                                                    object: nil,
                                                    userInfo: ["unRead":unRead,
                                                        "date":Date()])
                            CustomNotificationView.showNotificationPopUp(self.window!, name: friendName, msg: friendMsg, image: "", chat: chatID, friendID: friendId)

                            playSound()
                            print("Other Screen")
                        }
                    }
                }

            }else{

                print("app is in BG")

                var vc:ChatViewController!
                vc = ChatViewController(nibName: "ChatViewController", bundle: nil)
                vc.chatId = chatID
                vc.otherUserId = friendId
                vc.otherUserName = friendName
                vc.channelRef = self.channelRef.child("\(chatID)")
                vc.friendImageLink = "\(resourceUrl)\("")"

                let nav = UINavigationController(rootViewController: vc)
                nav.isNavigationBarHidden = false

                if let wd = self.window {
                    var VC = wd.rootViewController
                    if(VC is UINavigationController){
                        VC = (VC as! UINavigationController).visibleViewController
                    }


                    VC!.present(nav, animated: false, completion: {
                    })

                }


            }


        }

    }else{
        let val = userInfo["aps"] as! [String:AnyObject];
        let alert  =   NSString(string: val["alert"] as! String)
        if(UIApplication.shared.applicationState == UIApplicationState.inactive || UIApplication.shared.applicationState == UIApplicationState.background)
        {
            showUserInfo(application, didReceiveRemoteNotification: userInfo)
                      }
        else
        {

            print("top most vc \(String(describing: UIApplication.shared.keyWindow!.rootViewController!.topMostViewController().presentingViewController)) and presentedvc \(String(describing: UIApplication.shared.keyWindow!.rootViewController!.topMostViewController().presentedViewController))")

            if UIApplication.shared.keyWindow!.rootViewController!.topMostViewController() is NYAlertViewController{

                let newAlert = AppUtility?.getDisplayAlertController(title: "FitFlow", messageText: alert as String)
                let nvVc = UIApplication.shared.keyWindow!.rootViewController!.topMostViewController().presentedViewController
                nvVc?.present(newAlert!, animated: true, completion: nil)

                return

            }

                AppUtility?.displayAlert(title:"FitFlow", messageText: alert as String,UIApplication.shared.keyWindow!.rootViewController!.topMostViewController())




        }

    }
}

我已经通过保留断点进行了测试,它根本不调用didReceiveRemoteNotification 方法。如何使用上述方法接收推送通知?

【问题讨论】:

  • 你的有效载荷是什么样的?您是否在设备上启用了通知?您是在设备还是模拟器上进行测试?
  • 如果你的didReceiveRemoteNotification 根本没有被调用,那么请删除它的所有代码块,直到你找出它没有被击中的原因。我的意思是其余的代码没有必要查看帮助。
  • @Honey Hey 仍然无法找到解决方案???任何想法
  • - 生成 APNs 密钥。 firebase.google.com/docs/cloud-messaging/ios/certs - 上传 APNs 到 Firebase 项目的密钥。在 firebase 项目 => 设置 => 云消息 => iOS 应用程序配置 => APNs 身份验证密钥 - 还要确保您的应用程序在首次启动时请求通知权限。 // 向用户请求权限 FCM.requestPermissions(); FCM.getToken()
  • 你不觉得吗,在尚未尝试/回复 cmets 时添加赏金是没用的。

标签: ios swift firebase-cloud-messaging


【解决方案1】:

我之前也遇到过这个问题。

这需要 FCM 令牌,而不是 APNS 令牌

为此, 您的 AppDelegate 类需要这些 -

import Firebase
import UserNotifications
import FirebaseMessaging

class AppDelegate: UIResponder,
                   UIApplicationDelegate,
                UNUserNotificationCenterDelegate,
                FIRMessagingDelegate {
                
                }
  • 然后订阅didFinishLaunchingWithOptions中的消息传递委托
func application(_ application: UIApplication,
                 didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    
    GIDSignIn.sharedInstance().clientID =
    "Your client id"
    DispatchQueue.main.async {
        FIRApp.configure()
    }
    
    FIRMessaging.messaging().remoteMessageDelegate = self


    if #available(iOS 10, *) {
        UNUserNotificationCenter.current().requestAuthorization(options:[.badge, .alert, .sound]){ (granted, error) in }
        application.registerForRemoteNotifications()
    }
        // iOS 9 support
    else if #available(iOS 9, *) {
        UIApplication.shared.registerUserNotificationSettings(UIUserNotificationSettings(types: [.badge, .sound, .alert], categories: nil))
        UIApplication.shared.registerForRemoteNotifications()
    }
        // iOS 8 support
    else if #available(iOS 8, *) {
        UIApplication.shared.registerUserNotificationSettings(UIUserNotificationSettings(types: [.badge, .sound, .alert], categories: nil))
        UIApplication.shared.registerForRemoteNotifications()
    }
        // iOS 7 support
    else {
        application.registerForRemoteNotifications(matching: [.badge, .sound, .alert])
    }
    

    return true
}

// 你不再需要 didRegisterForRemoteNotificationsWithDeviceToken 方法了

 func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) { }

你从代表didRegisterForRemoteNotificationsWithDeviceToken收到的令牌没有用,

您需要使用 FIRInstanceID.instanceID().token()

在您的 applicationDidBecomeActive 中添加以下代码,这将检查 FCM 令牌刷新,并优雅地处理。

func applicationDidBecomeActive(_ application: UIApplication) {
    
    NotificationCenter.default.addObserver(self, selector:
        #selector(tokenRefreshNotification), name:
        NSNotification.Name.firInstanceIDTokenRefresh, object: nil)
}

@objc func tokenRefreshNotification(notification: NSNotification) {

    if let refreshedToken = FIRInstanceID.instanceID().token() {
        print("InstanceID token: \(refreshedToken)")
        UserDefaults.standard.set(refreshedToken, forKey: "deviceToken")
        self.sendFCMTokenToServer(token: refreshedToken)
    }
    /* 
    Connect to FCM since connection may
    have failed when attempted before having a token.
    */
    else { 
        connectToFcm()
    }
}

func updatePushNotificationWebservice() {
    /*
     if you want to save that token on your server 
     Do that here.
     else use the token any other way you want.
    */
}

func connectToFcm() {
     
        FIRMessaging.messaging().connect { (error) in
            if (error != nil) {
                print("Unable to connect with FCM. \(String(describing: error))")                   
            }
            else {
                print("Connected to FCM.")
                /*
                **this is the token that you have to use**
                print(FIRInstanceID.instanceID().token()!)
                if there was no connection established earlier,
                you can try sending the token again to server.
                */

                let token = FIRInstanceID.instanceID().token()!
                self.sendFCMTokenToServer(token: token)

            }
        }
}
    
    

使用从FIRInstanceID.instanceID().token()! 获得的令牌进行调试,并在 >project>Cloud 消息选项卡中使用具有相同令牌的推送通知 Firebase 控制台。

https://console.firebase.google.com/u/0/

【讨论】:

    【解决方案2】:

    从后端将优先级设置为高可以解决我的问题。

    请从 Firebase 控制台检查->云消息(左下项)发送推送通知。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-05-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多