ios - 从 Xcode Swift 重新启动应用程序后不再发送推送通知

标签 ios swift push-notification firebase-cloud-messaging

我终于可以通过 Firebase 在我的两个应用程序之间发送推送通知了。问题是 App1 只有在设备上全新安装时才有效。如果我停止并再次运行,即使 fcmToken 没有更改,项目推送通知也不会再传送,并且在 App2 中出现错误:

POST: 
    {"multicast_id":6763498783850594663,"success":0,"failure":1,"canonical_ids":0,"results":[{"error":"NotRegistered"}]}

意思是 Firebase 没有找到有效的 fcmToken 来发送推送。在 App1 上首先安装控制台打印:

didReceiveRegistrationToken: Firebase registration token: eI8nx-zroBU:APA91bG9gZeukgfsxobw4C3mg0Jhro06ALUQqtJwjfYxIwv4hIvjFwNWpSc_0JHPtl2FAGb-Jqwk7GL5pgki_Q_awOngA8yP66IG9fpWKQjEuS330N_c3yMAQvDUBCVo7wbFET_oEqLu

是正确的,因为我在 didReceiveRegistrationToken 委托(delegate)方法中设置了它,在第二次启动时 didReceiveRegistrationToken 给出了与以前相同的 token 。据我所知,如果交付了一个新的 fcmToken 是被调用的 didRefreshRegistrationToken,但我没有从该委托(delegate)方法中打印出来,所以似乎早期的 fcmToken 仍然有效。 你能看出我哪里设置错了吗?

didFinishLaunchingWithOptions:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        window?.tintColor = UIColor.blue
        // Use Firebase library to configure APIs
        FirebaseApp.configure()
        Messaging.messaging().delegate = self
        Crashlytics().debugMode = true
        Fabric.with([Crashlytics.self])
        // setting up notification delegate
        if #available(iOS 10.0, *) {
            //iOS 10.0 and greater
            UNUserNotificationCenter.current().delegate = self
            let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
            //Solicit permission from the user to receive notifications
            UNUserNotificationCenter.current().requestAuthorization(options: authOptions, completionHandler: { granted, error in
                DispatchQueue.main.async {
                    if granted {
                        print("didFinishLaunchingWithOptions iOS 10: Successfully registered for APNs")
                        UIApplication.shared.registerForRemoteNotifications() // declaring it work perfetcly
                        UIApplication.shared.applicationIconBadgeNumber = 0
                    } else {
                        //Do stuff if unsuccessful...
                        print("didFinishLaunchingWithOptions iOO 10: Error in registering for APNs: \(String(describing: error))")
                    }
                }
            })
        } else {
            //iOS 9
            let type: UIUserNotificationType = [UIUserNotificationType.badge, UIUserNotificationType.alert, UIUserNotificationType.sound]
            let setting = UIUserNotificationSettings(types: type, categories: nil)
            UIApplication.shared.registerUserNotificationSettings(setting)
            UIApplication.shared.registerForRemoteNotifications() // declaring it work perfetcly
            UIApplication.shared.applicationIconBadgeNumber = 0
            print("didFinishLaunchingWithOptions iOS 9: Successfully registered for APNs")
        }
        //get application instance ID
//        InstanceID.instanceID().instanceID { (result, error) in
//            if let error = error {
//                print("didFinishLaunchingWithOptions: Error fetching remote instance ID: \(error)")
//            } else if let result = result {
//                print("didFinishLaunchingWithOptions: Remote instance ID token: \(result.token)")
//            }
//        }
        // setting up remote control values
        let _ = RCValues.sharedInstance
        GIDSignIn.sharedInstance().clientID = FirebaseApp.app()?.options.clientID
        Crashlytics().debugMode = true
        Fabric.with([Crashlytics.self])
        //        // TODO: Move this to where you establish a user session
        //        self.logUser()
        var error: NSError?
        do {
            try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
        } catch let error1 as NSError{
            error = error1
            print("could not set session. err:\(error!.localizedDescription)")
        }
        do {
            try AVAudioSession.sharedInstance().setActive(true)
        } catch let error1 as NSError{
            error = error1
            print("could not active session. err:\(error!.localizedDescription)")
        }
        // goggle only
        GIDSignIn.sharedInstance().clientID = FirebaseApp.app()?.options.clientID
//        GIDSignIn.sharedInstance().delegate = self
        // Facebook SDK
        return FBSDKApplicationDelegate.sharedInstance().application(application, didFinishLaunchingWithOptions: launchOptions)
//        return true
    }

didRegisterForRemoteNotificationsWithDeviceToken:

func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        let tokenParts = deviceToken.map { data -> String in
            return String(format: "%02.2hhx", data)
        }
        let token = tokenParts.joined()
        print(" didRegisterForRemoteNotificationsWithDeviceToken : devcice token is: \(token)")
        Messaging.messaging().apnsToken = deviceToken
    }

didReceiveRegistrationToken:

func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) {
        print("didReceiveRegistrationToken: Firebase registration token: \(fcmToken)")
        let dataDict:[String: String] = ["token": fcmToken]
        NotificationCenter.default.post(name: Notification.Name("FCMToken"), object: nil, userInfo: dataDict)
        // TODO: If necessary send token to application server.
        AppDelegate.fcmToken = fcmToken

        if userDetails.fullName != nil {
            userDetails.fcmToken = fcmToken
            Firebase.updateToken(completed: { (true) in
                print("AppDelegate.didFinishLaunchingWithOptions: token updloaded to Firebase, will now save it to CoreData")
            }, token: fcmToken)
        }
        // Note: This callback is fired at each app startup and whenever a new token is generated.
    }

didRefreshRegistrationToken:

func messaging(_ messaging: Messaging, didRefreshRegistrationToken fcmToken: String) {
        let dataDict:[String: String] = ["token": fcmToken]
        NotificationCenter.default.post(name: Notification.Name("FCMToken"), object: nil, userInfo: dataDict)
//        print("Refreshed Token: \(fcmToken)")
        AppDelegate.fcmToken = fcmToken
        if userDetails.fullName != nil {
            userDetails.fcmToken = fcmToken
            Firebase.updateToken(completed: { (true) in
                print("AppDelegate.didRefreshRegistrationToken: token updloaded to Firebase, will now save it to CoreData")
            }, token: fcmToken)
        }
    }

最佳答案

问题似乎解决了。更新 pod 后,它现在可以按预期工作。我不得不从设备中删除 App1 并尽快重新安装它,我第一次尝试再次运行该项目时问题仍然存在。清理构建后,从设备中删除应用程序并重新安装它现在在我重新启动项目后继续接收推送通知。 希望这会对其他人有所帮助,因为我在实现设备到设备推送通知方面付出了很多努力,并且没有找到很多有用的信息。

关于ios - 从 Xcode Swift 重新启动应用程序后不再发送推送通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56341692/

相关文章:

ios - 应用扩展 "Terminated due to memory issue"

ios - 为什么在 iPad 上,self.clearsContextBeforeDrawing = NO;不会使 drawRect 在绘制之前不清除自身

ios - 用于打开帖子的 Facebook URL 方案

swift - NSTableRowView 拖放时的奇怪行为(在 View 层次结构中不断插入 NSView)

objective-c - Swift 转换为数组和字典

push-notification - 在 iPhone 上推送通知而不向用户发出警报

iphone - 将文件保存到 Web View 可以看到的用户设备

objective-c - 将 iPhone 应用程序转换为 iPad,然后在 iPad 中使用 splitview?

ios - 为什么从 Nib 加载的 UITextField 默认字体太小?

android - 如何创建从本地服务器到 Android 设备的推送通知 - 没有 GCM,没有互联网连接