热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

FCM+Swift3-Notificationsnotappearing

Iknowyouvestumbledacrossthisquestionbefore;severaltimesinfact.ButIhavefollowedEVERY

I know you've stumbled across this question before; several times in fact. But I have followed EVERY suggestion provided to me here, here, and even here.

我知道你之前偶然发现了这个问题;事实上好几次。但我已经按照我在这里提供给我的每一个建议,甚至在这里。

(Written in Swift 3, running on Xcode 8.1)

(用Swift 3编写,在Xcode 8.1上运行)

Yes, my PUSH NOTIFICATIONS in Capabilities are on. And even my Background Modes Remote Capabilities is on - I've tried toggling the FirebaseAppDelegateProxy On and Off, checked the certificates (why, yes, it is pointing to the correct App bundle), moved the

是的,我的功能通知已经开启。甚至我的后台模式远程功能开启 - 我尝试打开和关闭FirebaseAppDelegateProxy,检查证书(为什么,是的,它指向正确的应用程序包),移动了

application.registerForRemoteNotifications()

Cried, consumed copious amounts of sugar, prayed to God and then what ever other related deities I could think of, and still - naught.

哭了,消耗了大量的糖,向上帝祈祷,然后向我所能想到的其他相关神灵祈祷,但仍然 - 没有。

It could just be a screaming need for a second set of eyes, but any ideas?

它可能只是对第二组眼睛的尖叫需求,但任何想法?

import UIKit
import UserNotifications

import Firebase
import FirebaseMessaging


@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?
    let gcmMessageIDKey = "gcm.message_id"


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

        // Override point for customization after application launch.
        // [START register_for_notifications]
        if #available(iOS 10.0, *) {
            let authOptions : UNAuthorizatiOnOptions= [.alert, .badge, .sound]
            UNUserNotificationCenter.current().requestAuthorization(
                options: authOptions,
                completionHandler: {_,_ in })

            // For iOS 10 display notification (sent via APNS)
            UNUserNotificationCenter.current().delegate = self
            // For iOS 10 data message (sent via FCM)
            FIRMessaging.messaging().remoteMessageDelegate = self

        } else {
            let settings: UIUserNotificatiOnSettings=
                UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
            application.registerUserNotificationSettings(settings)
        }

        application.registerForRemoteNotifications()

        // Add observer for InstanceID token refresh callback.
        NotificationCenter.default.addObserver(self,
                                                         selector: #selector(self.tokenRefreshNotification),
                                                         name: NSNotification.Name.firInstanceIDTokenRefresh,
                                                         object: nil)

        return true
    }

    func tokenRefreshNotification(_ notification: Notification) {
        if let refreshedToken = FIRInstanceID.instanceID().token() {
            print("InstanceID token: \(refreshedToken)")
        }

        // Connect to FCM since connection may have failed when attempted before having a token.
        connectToFcm()
    }

    // [START connect_to_fcm]
    func connectToFcm() {
        FIRMessaging.messaging().connect { (error) in
            if error != nil {
                print("Unable to connect with FCM. \(error)")
            } else {
                print("Connected to FCM.")
            }
        }
    }
    // [END connect_to_fcm]

    func applicationWillResignActive(_ application: UIApplication) {
        // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
        // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
    }

    func applicationDidEnterBackground(_ application: UIApplication) {
        // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
        // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    }

    func applicationWillEnterForeground(_ application: UIApplication) {
        // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
    }

    func applicationDidBecomeActive(_ application: UIApplication) {
        // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    }

    func applicationWillTerminate(_ application: UIApplication) {
        // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    }


    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {
        // 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

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

        // Print full message.
        print(userInfo)
    }

    private func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
//        let tokenChars = deviceToken.bytes
        var tokenString = ""

        for i in 0..

And here are the extensions...

以下是扩展......

import Foundation
import UserNotifications
import FirebaseMessaging

@available(iOS 10, *)
extension AppDelegate : UNUserNotificationCenterDelegate {

    // Receive displayed notifications for iOS 10 devices.

    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        let userInfo = notification.request.content.userInfo
        // Print message ID.
        print("Message ID: \(userInfo["gcm.message_id"]!)")

        // Print full message.
        print("%@", userInfo)

    }

}

extension AppDelegate : FIRMessagingDelegate {
    // Receive data message on iOS 10 devices.
    func applicationReceivedRemoteMessage(_ remoteMessage: FIRMessagingRemoteMessage) {
        print("%@", remoteMessage.appData)
    }
}

Tokens are logging into the console, FCM is connected, Cloud Messaging is holding my certificates... the only possible hint I MAY have is that Firebase Console doesn't count the one device it is sending a message to as being 'Sent'.

令牌正在登录控制台,FCM已连接,云消息传递正在保存我的证书...我可能唯一可能的提示是Firebase控制台不会将发送消息的设备计为“已发送”。

enter image description here But the console looks fine.

但控制台看起来很好。

2016-12-15 00:07:05.344 voltuser[4199:2008900] WARNING: Firebase Analytics App Delegate Proxy is disabled. To log deep link campaigns manually, call the methods in FIRAnalytics+AppDelegate.h.
2016-12-15 00:07:05.349 voltuser[4199:2008900] Firebase automatic screen reporting is enabled. Call +[FIRAnalytics setScreenName:setScreenClass:] to set the screen name or override the default screen class name. To disable automatic screen reporting, set the flag FirebaseAutomaticScreenReportingEnabled to NO in the Info.plist
2016-12-15 00:07:05.447 voltuser[4199]  [Firebase/Core][I-COR000001] Configuring the default app.
2016-12-15 00:07:05.514:  Failed to fetch APNS token Error Domain=com.firebase.iid Code=1001 "(null)"
2016-12-15 00:07:05.520:  FIRMessaging library version 1.2.0
2016-12-15 00:07:05.549 voltuser[4199:]  Firebase Analytics v.3600000 started
2016-12-15 00:07:05.549 voltuser[4199:]  To enable debug logging set the following application argument: -FIRAnalyticsDebugEnabled (see this)
2016-12-15 00:07:05.605 voltuser[4199]  [Firebase/Core][I-COR000018] Already sending logs.
2016-12-15 00:07:05.679 voltuser[4199]  [Firebase/Core][I-COR000019] Clearcut post completed.
2016-12-15 00:07:05.782 voltuser[4199]  [Firebase/Core][I-COR000019] Clearcut post completed.
2016-12-15 00:07:05.824 voltuser[4199:]  The AdSupport Framework is not currently linked. Some features will not function properly. Learn more at here
2016-12-15 00:07:07.286 voltuser[4199:]  Firebase Analytics enabled
InstanceID token: c_4iSvTQcHw:APA91bGjKnPoH9LysKl9CQxCJRJsfqwXBSUFAmgRp-KEWKjWqe2j4nt6Y5gx8us41rB6eLnRCOwRntnbr_N1fh_swz8j-GvvChSsV3gvG8dufVFLpagdtOxrxPSgLubQrfw-JqkA-4wV
Connected to FCM.
And the snapshot says Snap (mx7zr3y6XpSGZ4uB4PhZ8QRHIvt2) 
[AnyHashable("notification"): {
    body = "THIS IS SO PAINFUL";
    e = 1;
    title = "WHY WONT YOU WORK";
}, AnyHashable("from"): 99570566728, AnyHashable("collapse_key"): com.mishastone.voltuser]

... but the message is logging just fine in my console. In fact, there are not outcrying errors at all!

...但是消息在我的控制台中正常记录。事实上,根本没有出现错误的错误!

sigh

My phone is not getting foreground, background or any sort of notification from the app - there's nothing. Zip. Zilch. Nada. Just the breaking sounds of my heart.

我的手机没有从应用程序获得前景,背景或任何类型的通知 - 没有任何东西。压缩。小人物。纳达。只是我心碎的声音。

My iPhone is currently on 9.3.5. If that helps any.

我的iPhone目前是9.3.5。如果这有帮助。

Any help would be greatly appreciated - or suggestions for alternative push notification systems...

任何帮助将不胜感激 - 或建议替代推送通知系统......

2 个解决方案

#1


10  

Figured it out. p.s. im using Swift 3 syntax, you are missing the completionhandler in your willPresent method

弄清楚了。附:我使用Swift 3语法,你缺少willPresent方法中的completionhandler

completionHandler The block to execute with the presentation option for the notification. Always execute this block at some point during your implementation of this method.

completionHandler使用通知的表示选项执行的块。始终在执行此方法期间的某个时刻执行此块。

https://developer.apple.com/reference/usernotifications/unusernotificationcenterdelegate/1649518-usernotificationcenter

https://developer.apple.com/reference/usernotifications/unusernotificationcenterdelegate/1649518-usernotificationcenter

func userNotificationCenter(_ center: UNUserNotificationCenter,
                            willPresent notification: UNNotification,
                            withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
    let userInfo = notification.request.content.userInfo as! [String: Any]



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

}

#2


0  

If you are sure about your code is perfect and still you are unable to receive FCM notifications then please update p12 certificate from Firebase console. You have to export only security key from Push certifcate and upload it . You will start receiving notifications.

如果您确定您的代码是完美的,但仍然无法接收FCM通知,请从Firebase控制台更新p12证书。您必须仅从Push certifcate导出安全密钥并上传它。您将开始接收通知。


推荐阅读
  • 浅析python实现布隆过滤器及Redis中的缓存穿透原理_python
    本文带你了解了位图的实现,布隆过滤器的原理及Python中的使用,以及布隆过滤器如何应对Redis中的缓存穿透,相信你对布隆过滤 ... [详细]
  • 单片微机原理P3:80C51外部拓展系统
      外部拓展其实是个相对来说很好玩的章节,可以真正开始用单片机写程序了,比较重要的是外部存储器拓展,81C55拓展,矩阵键盘,动态显示,DAC和ADC。0.IO接口电路概念与存 ... [详细]
  • 本文介绍如何使用 Python 的 DOM 和 SAX 方法解析 XML 文件,并通过示例展示了如何动态创建数据库表和处理大量数据的实时插入。 ... [详细]
  • 本项目通过Python编程实现了一个简单的汇率转换器v1.02。主要内容包括:1. Python的基本语法元素:(1)缩进:用于表示代码的层次结构,是Python中定义程序框架的唯一方式;(2)注释:提供开发者说明信息,不参与实际运行,通常每个代码块添加一个注释;(3)常量和变量:用于存储和操作数据,是程序执行过程中的重要组成部分。此外,项目还涉及了函数定义、用户输入处理和异常捕获等高级特性,以确保程序的健壮性和易用性。 ... [详细]
  • 如何将Python与Excel高效结合:常用操作技巧解析
    本文深入探讨了如何将Python与Excel高效结合,涵盖了一系列实用的操作技巧。文章内容详尽,步骤清晰,注重细节处理,旨在帮助读者掌握Python与Excel之间的无缝对接方法,提升数据处理效率。 ... [详细]
  • 为了确保iOS应用能够安全地访问网站数据,本文介绍了如何在Nginx服务器上轻松配置CertBot以实现SSL证书的自动化管理。通过这一过程,可以确保应用始终使用HTTPS协议,从而提升数据传输的安全性和可靠性。文章详细阐述了配置步骤和常见问题的解决方法,帮助读者快速上手并成功部署SSL证书。 ... [详细]
  • 深入解析C#中app.config文件的配置与修改方法
    在C#开发过程中,经常需要对系统的配置文件进行读写操作,如系统初始化参数的修改或运行时参数的更新。本文将详细介绍如何在C#中正确配置和修改app.config文件,包括其结构、常见用法以及最佳实践。此外,还将探讨exe.config文件的生成机制及其在不同环境下的应用,帮助开发者更好地管理和维护应用程序的配置信息。 ... [详细]
  • iOS Swift中如何实现自动登录?
    本文介绍了在iOS Swift中如何实现自动登录的方法,包括使用故事板、SWRevealViewController等技术,以及解决用户注销后重新登录自动跳转到主页的问题。 ... [详细]
  • Spring – Bean Life Cycle
    Spring – Bean Life Cycle ... [详细]
  • Spring Boot 中配置全局文件上传路径并实现文件上传功能
    本文介绍如何在 Spring Boot 项目中配置全局文件上传路径,并通过读取配置项实现文件上传功能。通过这种方式,可以更好地管理和维护文件路径。 ... [详细]
  • Ihavetwomethodsofgeneratingmdistinctrandomnumbersintherange[0..n-1]我有两种方法在范围[0.n-1]中生 ... [详细]
  • 本文对比了杜甫《喜晴》的两种英文翻译版本:a. Pleased with Sunny Weather 和 b. Rejoicing in Clearing Weather。a 版由 alexcwlin 翻译并经 Adam Lam 编辑,b 版则由哈佛大学的宇文所安教授 (Prof. Stephen Owen) 翻译。 ... [详细]
  • 开机自启动的几种方式
    0x01快速自启动目录快速启动目录自启动方式源于Windows中的一个目录,这个目录一般叫启动或者Startup。位于该目录下的PE文件会在开机后进行自启动 ... [详细]
  • Python多线程编程技巧与实战应用详解 ... [详细]
  • 2019 年 Firebase 峰会上发布的新功能
    作者FrancisMa,HeadofProductFirebase的使命是帮助移动开发者和Web开发者迈向成功,但考虑到Firebase每个月有超过200万个活跃的应 ... [详细]
author-avatar
samiensfe_663
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有