ios - 传入的推送通知设置警报两次 swift 4

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

我正在通过 Firebase 云消息传递实现推送通知,当我在设备上收到警报时,它实际上会广告两次,但在通知列表面板上,它按预期只出现一次。我正在尝试解决这个问题,但我是推送通知的新手,我找不到我在哪里设置了重复的 .我正在 iPad 3 上进行测试,并晒 iOs 9.3.5 。你能看看我是否在 didFinishLaunchingWithOptions 中设置了两次,或者我可以在哪里设置两次吗? 一如既往,非常感谢。

didFinishLaunchingWithOptions:

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

        //  UI Theme selection
        if UserDefaults.standard.object(forKey: "Theme") != nil {
            Theme.selectedTheme = UserDefaults.standard.bool(forKey: "Theme") ? 1 : 2
        }

        // setting up Firebase
        FirebaseApp.configure()
        Messaging.messaging().delegate = 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")

                    } 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)
            print("didFinishLaunchingWithOptions iOS 9: Successfully registered for APNs")

        }
        UIApplication.shared.registerForRemoteNotifications()


        //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()

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

        if #available(iOS 10.0, *) {
            // For iOS 10 display notification (sent via APNS)
            UNUserNotificationCenter.current().delegate = self
            Messaging.messaging().apnsToken = deviceToken // mandatory!!

            let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
            UNUserNotificationCenter.current().requestAuthorization(
                options: authOptions,
                completionHandler: {_, _ in })
        } else {
            Messaging.messaging().apnsToken = deviceToken // mandatory!!
            let settings: UIUserNotificationSettings =
                UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
            application.registerUserNotificationSettings(settings)
        }

    }

didReceiveRemoteNotification:

    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any],
                         fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
            print("didReceiveRemoteNotification with handler : Received new push Notification")
            // If you are receiving a notification message while your app is in the background,
            // this callback will not be fired till the user taps on the notification launching the application.
            // TODO: Handle data of notification

            // With swizzling disabled you must let Messaging know about the message, for Analytics
             Messaging.messaging().appDidReceiveMessage(userInfo)

            // Print message ID.
            if let messageID = userInfo[ fcmMessageIDKey] {
                print("didReceiveRemoteNotification: Message ID: \(messageID)")
            }

            // Print full message.
            print("didReceiveRemoteNotification: Push notificationMessage is: \(userInfo)")

            completionHandler(UIBackgroundFetchResult.newData)
        }

打开通知时控制台打印:

didReceiveRemoteNotification with handler : Received new push Notification
didReceiveRemoteNotification: Push notificationMessage is: [AnyHashable("google.c.a.c_id"): 1354763473839437035, AnyHashable("google.c.a.udt"): 0, AnyHashable("gcm.notification.sound2"): enabled, AnyHashable("gcm.n.e"): 1, AnyHashable("gcm.message_id"): 0:1558780267039787%6f9b8aab6f9b8aab, AnyHashable("google.c.a.ts"): 1558780266, AnyHashable("google.c.a.tc"): 1, AnyHashable("google.c.a.e"): 1, AnyHashable("google.c.a.c_l"): Test push , AnyHashable("aps"): {
    alert = "First push test";
    badge = 0;
    sound = enabled;
}]
May 25 12:31:23  fix-it shop[406] <Debug>: 5.20.0 - [Firebase/Messaging][I-FCM019003] FIRMessagingAnalytics: Sending event: _cmp params: {
        campaign = 1354763473839437035;
        medium = notification;
        source = Firebase;
    }
May 25 12:31:23  fix-it shop[406] <Debug>: 5.20.0 - [Firebase/Messaging][I-FCM019005] FIRMessagingAnalytics: Sending event: _no params: {
        "_ndt" = 0;
        "_nmid" = 1354763473839437035;
        "_nmn" = "Test push ";
        "_nmt" = 1558780266;
    }
May 25 12:31:23  fix-it shop[406] <Debug>: 5.20.0 - [Firebase/Messaging][I-FCM006000] Received message missing local start time, dropped.
May 25 12:31:23  fix-it shop[406] <Debug>: 5.20.0 - [Firebase/Analytics][I-ACS023080] Setting user property. Name, value: firebase_last_notification (_ln), 1354763473839437035
May 25 12:31:23  fix-it shop[406] <Debug>: 5.20.0 - [Firebase/Analytics][I-ACS023087] User property set. Name, value: firebase_last_notification (_ln), 1354763473839437035
May 25 12:31:23  fix-it shop[406] <Debug>: 5.20.0 - [Firebase/Analytics][I-ACS023051] Logging event: origin, name, params: fcm, firebase_campaign (_cmp), {
        _cis = fcm_integration;
        campaign = 1354763473839437035;
        ga_event_origin (_o) = fcm;
        medium = notification;
        source = Firebase;
    }
May 25 12:31:23  fix-it shop[406] <Debug>: 5.20.0 - [Firebase/Analytics][I-ACS023073] Debug mode is enabled. Marking event as debug and real-time. Event name, parameters: firebase_campaign (_cmp), {
        _cis = fcm_integration;
        campaign = 1354763473839437035;
        firebase_debug (_dbg) = 1;
        ga_event_origin (_o) = fcm;
        ga_realtime (_r) = 1;
        medium = notification;
        source = Firebase;
    }
May 25 12:31:24  fix-it shop[406] <Debug>: 5.20.0 - [Firebase/Analytics][I-ACS033003] Scheduling user engagement timer
May 25 12:31:24  fix-it shop[406] <Debug>: 5.20.0 - [Firebase/Analytics][I-ACS002002] Engagement timer scheduled to fire in approx. (s): 3600
May 25 12:31:24  fix-it shop[406] <Debug>: 5.20.0 - [Firebase/Analytics][I-ACS023072] Event logged. Event name, event params: firebase_campaign (_cmp), {
        _cis = fcm_integration;
        campaign = 1354763473839437035;
        firebase_debug (_dbg) = 1;
        ga_event_origin (_o) = fcm;
        ga_realtime (_r) = 1;
        medium = notification;
        source = Firebase;
    }
May 25 12:31:24  fix-it shop[406] <Debug>: 5.20.0 - [Firebase/Analytics][I-ACS002002] Measurement timer scheduled to fire in approx. (s): -0.09409010410308838
May 25 12:31:24  fix-it shop[406] <Debug>: 5.20.0 - [Firebase/Analytics][I-ACS023028] Upload task scheduled to be executed in approx. (s): -0.09409010410308838
May 25 12:31:24  fix-it shop[406] <Debug>: 5.20.0 - [Firebase/Analytics][I-ACS023051] Logging event: origin, name, params: fcm, notification_open (_no), {
        ga_event_origin (_o) = fcm;
        message_device_time (_ndt) = 0;
        message_id (_nmid) = 1354763473839437035;
        message_name (_nmn) = Test push ;
        message_time (_nmt) = 1558780266;
    }
May 25 12:31:24  fix-it shop[406] <Debug>: 5.20.0 - [Firebase/Analytics][I-ACS023073] Debug mode is enabled. Marking event as debug and real-time. Event name, parameters: notification_open (_no), {
        firebase_debug (_dbg) = 1;
        ga_event_origin (_o) = fcm;
        ga_realtime (_r) = 1;
        message_device_time (_ndt) = 0;
        message_id (_nmid) = 1354763473839437035;
        message_name (_nmn) = Test push ;
        message_time (_nmt) = 1558780266;
    }
May 25 12:31:24  fix-it shop[406] <Debug>: 5.20.0 - [Firebase/Analytics][I-ACS023072] Event logged. Event name, event params: notification_open (_no), {
        firebase_debug (_dbg) = 1;
        ga_event_origin (_o) = fcm;
        ga_realtime (_r) = 1;
        message_device_time (_ndt) = 0;
        message_id (_nmid) = 1354763473839437035;
        message_name (_nmn) = Test push ;
        message_time (_nmt) = 1558780266;
    }
May 25 12:31:24  fix-it shop[406] <Debug>: 5.20.0 - [Firebase/Analytics][I-ACS023027] Do not schedule an upload task. Task already exists. Will be executed in seconds: -0.3860381841659546
May 25 12:31:24  fix-it shop[406] <Debug>: 5.20.0 - [Firebase/Analytics][I-ACS002001] Measurement timer fired
May 25 12:31:24  fix-it shop[406] <Debug>: 5.20.0 - [Firebase/Analytics][I-ACS002003] Measurement timer canceled
May 25 12:31:24  fix-it shop[406] <Debug>: 5.20.0 - [Firebase/Analytics][I-ACS023033] Starting data upload
May 25 12:31:24  fix-it shop[406] <Debug>: 5.20.0 - [Firebase/Analytics][I-ACS023105] Event is not subject to real-time event count daily limit. Marking an event as real-time. Event name, parameters: firebase_campaign (_cmp), {
        _cis = fcm_integration;
        campaign = 1354763473839437035;
        firebase_debug (_dbg) = 1;
        ga_event_origin (_o) = fcm;
        ga_realtime (_r) = 1;
        medium = notification;
        source = Firebase;
    }
May 25 12:31:24  fix-it shop[406] <Debug>: 5.20.0 - [Firebase/Analytics][I-ACS023105] Event is not subject to real-time event count daily limit. Marking an event as real-time. Event name, parameters: notification_open (_no), {
        firebase_debug (_dbg) = 1;
        ga_event_origin (_o) = fcm;
        ga_realtime (_r) = 1;
        message_device_time (_ndt) = 0;
        message_id (_nmid) = 1354763473839437035;
        message_name (_nmn) = Test push ;
        message_time (_nmt) = 1558780266;
    }
May 25 12:31:24  fix-it shop[406] <Debug>: 5.20.0 - [Firebase/Analytics][I-ACS012018] Saving bundle. size (bytes): 543
May 25 12:31:24  fix-it shop[406] <Debug>: 5.20.0 - [Firebase/Analytics][I-ACS023116] Bundle added to the upload queue. BundleID, timestamp (ms): 81, 1558780283193
May 25 12:31:24  fix-it shop[406] <Debug>: 5.20.0 - [Firebase/Analytics][I-ACS023038] Uploading events. Elapsed time since last successful upload (s): 275.0853600502014
May 25 12:31:24  fix-it shop[406] <Debug>: 5.20.0 - [Firebase/Analytics][I-ACS023039] Measurement data sent to network. Timestamp (ms), data: 1558780284672, <APMPBMeasurementBatch: 0x16ef3490>
May 25 12:31:24  fix-it shop[406] <Debug>: 5.20.0 - [Firebase/Analytics][I-ACS900000] Uploading data. Host: https://app-measurement.com/a
May 25 12:31:24  fix-it shop[406] <Debug>: 5.20.0 - [Firebase/Analytics][I-ACS901006] Received SSL challenge for host. Host: https://app-measurement.com/a
May 25 12:31:24  fix-it shop[406] <Debug>: 5.20.0 - [Firebase/Analytics][I-ACS023044] Successful upload. Got network response. Code, size: 204, 0
May 25 12:31:24  fix-it shop[406] <Debug>: 5.20.0 - [Firebase/Analytics][I-ACS002002] Measurement timer scheduled to fire in approx. (s): -0.7099969387054443
May 25 12:31:24  fix-it shop[406] <Debug>: 5.20.0 - [Firebase/Analytics][I-ACS023028] Upload task scheduled to be executed in approx. (s): -0.7099969387054443
May 25 12:31:24  fix-it shop[406] <Debug>: 5.20.0 - [Firebase/Analytics][I-ACS023024] No data to upload. Upload task will not be scheduled
May 25 12:31:24  fix-it shop[406] <Debug>: 5.20.0 - [Firebase/Analytics][I-ACS002003] Measurement timer canceled

最佳答案

我发现了错误。在 didFinishLaunchingWithOptions 中设置通知后,我再次在 didRegisterForRemoteNotificationsWithDeviceToken 中设置通知。因此,在该方法中,我只处理收到的 token 。

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 // mandatory!!

    }

希望这对其他人有帮助。

关于ios - 传入的推送通知设置警报两次 swift 4,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56303976/

相关文章:

使用 Sockets 的 iPhone 通信

ios - 无法使用 JSON 解码器解析 JSON

Azure 通知中心和设置设备安装的过期时间

ios - 从 SQLite 数据库获取 UITableView 中的 NULL 值

IOS - 从 IOS 应用程序中的另一个类写入 UITextField

ios - 如何快速使用苹果的 Accelerate 框架来计算真实信号的 FFT?

swift - Swift 中从 UIButton (UIColor) backgroundColor 获取 RGB 颜色

objective-c - 为 OS X 实现 float 按钮 UI View 的最简单方法是什么

iOS 推送通知不适用于带有 Test Flight 的临时分发

ios 10 推送通知媒体附件随机不起作用