Firebase在Xcode 8.3上发布iOS 10.3 Swift 3 FCM通知无效 [英] Firebase Issues iOS 10.3 on Xcode 8.3 Swift 3 FCM notifications not working

查看:1755
本文介绍了Firebase在Xcode 8.3上发布iOS 10.3 Swift 3 FCM通知无效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Swift 3 iOS 10.3.2 开发 Xcode 8.3.2 ,我的项目使用firebase云消息传递我的

证书过期了,我更新了我的证书 p12 p8 建议的Firebase文档,但推送通知停止了,昨天当我使用控制台firebase测试,它正在工作,但今天不,日志打印我这是正常的:

  2017-05-30 10 :13:23.932066-0400大声笑[5576:1530669]警告:Firebase Analytics App委托代理被禁用。要手动记录深层链接活动,请在FIRAnalytics + AppDelegate.h中调用方法。 
2017-05-30 10:13:23.949512-0400大声笑[5576:1530669]启用了Firebase自动屏幕报告功能。调用+ [FIRAnalytics setScreenName:setScreenClass:]设置屏幕名称或覆盖默认的屏幕类名称。要禁用自动屏幕报告,请在Info.plist中设置标志FirebaseAutomaticScreenReportingEnabled为NO
2017-05-30 10:13:24.368364-0400大声笑[5576:1530669] [Crashlytics]版本3.8.2(118)
2017-05-30 10:13:24.397942-0400 lol [5576:1530669] [MC] systemgroup.com.apple.configurationprofiles路径的系统组容器路径为/ private / var / containers / Shared / SystemGroup / systemgroup。 com.apple.configurationprofiles
2017-05-30 10:13:24.398433-0400大声笑[5576:1530669] [MC]从公共有效的用户设置读取。
initializeFCM
已接受通知访问。
2017-05-30 10:13:24.679:< FIRInstanceID / WARNING>无法获取APNS令牌Error Domain = com.firebase.iid Code = 1001(null)
2017-05-30 10:13:24.681:< FIRMessaging / INFO> FIRMessaging库版本1.2.0
2017-05-30 10:13:24.683213-0400大声笑[5576:1530706] [Firebase / Crash] [I-CRA000004]成功初始化
2017-05-30 10 :13:24.683 lol<注意> [Firebase / Crash] [I-CRA000004]成功初始化
2017-05-30 10:13:24.685110-0400大声笑[5576:1530706]< FIRAnalytics / INFO> Firebase Analytics v.3600000开始
2017-05-30 10:13:24.685大声笑[5576:]< FIRAnalytics / INFO> Firebase Analytics v.3600000开始
2017-05-30 10:13:24.685438-0400大声笑[5576:1530706]< FIRAnalytics / INFO>要启用调试日志记录,请设置以下应用程序参数:-FIRAnalyticsDebugEnabled
2017-05-30 10:13:24.685大声笑[5576:]< FIRAnalytics / INFO>要启用调试日志记录设置以下应用程序参数:-FIRAnalyticsDebugEnabled
GCM TOKEN =可选(\它的工作:请帮助STACKOVERFLOW\)
didRegisterForRemoteNotificationsWithDeviceToken:DATA
*** deviceToken:< 66666666它正在工作:请帮助STACKOVERFLOW 99999999>
2017-05-30 10:13:24.837:< FIRInstanceID / WARNING> APNS环境在配置文件:开发
Firebase令牌:可选(正在工作:请帮助STACKOVERFLOW)
2017-05-30 10:13:24.932076-0400大声笑[5576:1530727]< FIRAnalytics /信息>已启用Firebase Analytics
2017-05-30 10:13:24.932 lol [5576:]< FIRAnalytics / INFO>已启用Firebase Analytics
已连接到FCM。

新奇怪的日志是:

  2017-05-30 10:13:24.679:< FIRInstanceID / WARNING>无法获取APNS令牌Error Domain = com.firebase.iid Code = 1001(null)

我的代码是:

  // 
// AppDelegate.swift
// lol
//
//由Dennis Mostajo于06/06/16创建。 ---> 666号的野兽! O_O!
//版权所有©2016 Dennis Mostajo。版权所有。
//

导入UIKit

导入FirebaseAnalytics
导入FirebaseInstanceID
导入FirebaseMessaging
导入UserNotifications

@UIApplicationMain
class AppDelegate:UIResponder,UIApplicationDelegate,UNUserNotificationCenterDelegate {

var window:UIWindow?


func application(_ application:UIApplication,didFinishLaunchingWithOptions launchOptions:[UIApplicationLaunchOptionsKey:Any]?) - > Bool
{
//应用程序启动后自定义的覆盖点。
self.initializeFCM(application)
let token = FIRInstanceID.instanceID()。token()
debugPrint(GCM TOKEN = \(String(describe:token)))
返回true


func application(_ application:UIApplication,didFailToRegisterForRemoteNotificationsWithError error:Error)
{
debugPrint(didFailToRegisterForRemoteNotificationsWithError:\(error) )
}

func applicationReceivedRemoteMessage(_ remoteMessage:FIRMessagingRemoteMessage)
{
debugPrint(remoteMessage:\(remoteMessage.appData))
}

func initializeFCM(_ application:UIApplication)
{
print(initializeFCM)
// ------------- -------------------------------------------------- ---------- //
if #available(iOS 10.0,*)//在iOS 10上启用通知的新方法
{
let center = UNUserNotificationCenter .current()
center.delegate = self
center.requestAuthorization(options:[.badge,.alert,.sound]){(accepted,error)in
if!accepted
$ b print(Notification access denied。)
}
else
{
print(Notification access accepted。)
UIApplication。 shared.registerForRemoteNotifications();



$ b {
let type:UIUserNotificationType = [UIUserNotificationType.badge,UIUserNotificationType.alert,UIUserNotificationType.sound];
让setting = UIUserNotificationSettings(类型:类型,类别:nil);
UIApplication.shared.registerUserNotificationSettings(setting);
UIApplication.shared.registerForRemoteNotifications();


FIRApp.configure()

NotificationCenter.default.addObserver(self,selector:#selector(self.tokenRefreshNotificaiton),
name: NSNotification.Name.firInstanceIDTokenRefresh,object:nil)
}

func registrationhandler(_registrationToken:String !,错误:NSError!)
{
if(registrationToken! =
debugPrint(registrationToken = \(String(descriptions:registrationToken)))
}
else
{
debugPrint( 注册到GCM失败,错误:\(error.localizedDescription))
}
}

func tokenRefreshNotificaiton(_ notification:Foundation.Notification)
{
if let refreshedToken = FIRInstanceID.instanceID()。token()
{
debugPrint(InstanceID token:\(refreshedToken))
}
connectToFcm()
}

func connectToFcm()
{
//不会连接,因为没有令牌
guard FIRInstanceID。 instanceID()。token()!= nil else
{
return;
}
//断开以前的FCM连接(如果存在)。
FIRMessaging.messaging()。disconnect()
FIRMessaging.messaging()。connect {(error)in $ b $ if(error!= nil)
{
debugPrint (无法连接FCM。\(String(describe:error)))
}
else
{
debugPrint(Connected to FCM。)


$ b func application(_ application:UIApplication,didRegister notificationSettings:UIUserNotificationSettings)
{
debugPrint(didRegister notificationSettings)
if(notificationSettings.types == .alert || notificationSettings.types == .badge || notificationSettings.types == .sound)
{
application.registerForRemoteNotifications()
}


func application(application:UIApplication,didRegisterForRemoteNotificationsWithDeviceToken deviceToken:NSData)
{
debugPrint(didRegisterForRemoteNotificationsWithDeviceToken:NSDATA)

let token = String(format:%@,deviceToken as CVarArg)
debugPrint(*** deviceToken:\(token) )
#if RELEASE_VERSION
FIRInstanceID.instanceID()。setAPNSToken(deviceToken as Data,type:FIRInstanceIDAPNSTokenType.prod)
#else
FIRInstanceID.instanceID()。setAPNSToken(deviceToken as数据类型:FIRInstanceIDAPNSTokenType.sandbox)
#endif
debugPrint(Firebase Token:,FIRInstanceID.instanceID()。token()as Any)
}

@available(iOS 10.0,*)
func userNotificationCenter(_ center:UNUserNotificationCenter,willPresent notification:UNNotification,withCompletionHandler completionHandler:@escaping(UNNotificationPresentationOptions) - >无效)
{
//在APP前台处理通知
debugPrint(*** willPresent notification)
debugPrint(*** notification:\(notification) )

$ b @available(iOS 10.0,*)
func userNotificationCenter(_ center:UNUserNotificationCenter,didReceive响应:UNNotificationResponse,withCompletionHandler completionHandler:@escaping() - >无效)
{
//处理通知ON背景
debugPrint(*** didReceive响应通知)
debugPrint(*** response:\(response) )


func application(_ application:UIApplication,didRegisterForRemoteNotificationsWithDeviceToken deviceToken:Data)
{
debugPrint(didRegisterForRemoteNotificationsWithDeviceToken:DATA)
let token = String(format:%@,deviceToken as CVarArg)
debugPrint(*** deviceToken:\(token))
#if RELE ASE_VERSION
FIRInstanceID.instanceID()。setAPNSToken(deviceToken as Data,type:FIRInstanceIDAPNSTokenType.prod)
#else
FIRInstanceID.instanceID()。setAPNSToken(deviceToken as Data,type:FIRInstanceIDAPNSTokenType.sandbox )
#endif
debugPrint(Firebase Token:,FIRInstanceID.instanceID()。token()as Any)
}

func application(_ application: UIApplication,didReceiveRemoteNotification userInfo:[AnyHashable:Any],
fetchCompletionHandler completionHandler:@escaping(UIBackgroundFetchResult) - >无效){
//如果您的应用程序在后台收到通知消息,
//只有当用户点击启动应用程序的通知时,才会触发此回调。
// TODO:处理通知数据
FIRMessaging.messaging()。appDidReceiveMessage(userInfo)
$ b $如果让messageID = userInfo [gcm.message_id] {
debugPrint(Message ID:\(messageID))
}
debugPrint(*** userInfo:\(userInfo))


//打印完整的信息。
completionHandler(.newData)
}

func application(_ application:UIApplication,didReceive notification:UILocalNotification)
{
if application.applicationState!= UIApplicationState.active

if gcmMessageType = GCMMessageType(rawValue:notificationType)
{
debugPrint(didReceiveLocalNotification)
debugPrint(notification:\(notification ))


//application.applicationIconBadgeNumber = 0


$ b func applicationWillResignActive(_ application:UIApplication){
//当应用程序即将从活动状态转移到非活动状态时发送。对于某些类型的临时中断(例如来电或SMS消息)或用户退出应用程序并开始转换到后台状态时,可能会发生这种情况。
//使用此方法暂停正在进行的任务,禁用定时器,并使图形呈现回调无效。游戏应该使用这种方法来暂停游戏。

$ b $ func applicationDidEnterBackground(_ application:UIApplication){
//使用此方法释放共享资源,保存用户数据,使计时器无效并将足够的应用程序状态信息存储到如果稍后终止,则将应用程序恢复到当前状态。
//如果您的应用程序支持后台执行,则调用此方法而不是applicationWillTerminate:当用户退出时。


func applicationWillEnterForeground(_ application:UIApplication){
//作为从背景转换到活动状态的一部分;在这里你可以撤消进入背景的许多变化。


func applicationDidBecomeActive(_ application:UIApplication)
{
//在应用程序处于非活动状态时,重新启动暂停(或尚未启动)的任何任务。如果应用程序以前位于后台,则可以选择刷新用户界面。
connectToFcm()
}

func applicationWillTerminate(_ application:UIApplication){
//当应用程序即将终止时调用。保存数据,如果适用。另请参阅applicationDidEnterBackground :.




$ b我犯了一些错误,或者我需要配置一些东西,还有一些东西会因为iOS9和iOS10.3之间的不同而增加,或者增加到firebase的设置上,非常感谢您的帮助。



// -------------------------------------- -------------------------------------------------- -------------------------------------- //



编辑:

我已将Firebase更新至最新版本4.0.0,代码:
$ b

  func initializeFCM(_ application:UIApplication)
{
print(initializeFCM)
// --------------------------------------------- ---------------------------- //
if #available(iOS 10.0,*)//启用通知的新方法在iOS 10
{
让中心= UNUserNotificationCenter.current()
中心。
$ {
print(通知访问被拒绝。)
}
else
{
print(Notification access accepted。)
UIApplication.shared.registerForRemoteNotifications();



$ b {
let type:UIUserNotificationType = [UIUserNotificationType.badge,UIUserNotificationType.alert,UIUserNotificationType.sound];
让setting = UIUserNotificationSettings(类型:类型,类别:nil);
UIApplication.shared.registerUserNotificationSettings(setting);
UIApplication.shared.registerForRemoteNotifications();
}
// --------------------------------------- ---------------------------------- //

FirebaseApp.configure()
Messaging.messaging()。shouldEstablishDirectChannel = true

NotificationCenter.default.addObserver(self,selector:#selector(self.tokenRefreshNotificaiton),
name:NSNotification.Name.InstanceIDTokenRefresh,对象:无)
}

func应用程序(应用程序:UIApplication,didRegisterForRemoteNotificationsWithDeviceToken deviceToken:NSData)
{
debugPrint(didRegisterForRemoteNotificationsWithDeviceToken:NSDATA)

let token = String(format:%@,deviceToken as CVarArg)
debugPrint(*** deviceToken:\(token))
Messaging.messaging()。apnsToken = deviceToken as Data
debugPrint(Firebase Token:,InstanceID.instanceID()。token()as Any)
}

func application(_ application:UIApplication,didRegisterForRemoteNotificationsWithDeviceToken deviceToken:Data)
{
debugPrint(didRegisterForRemoteNotificationsWithDeviceToken:DATA)
let token = String(format:%@,deviceToken as CVarArg)
debugPrint(*** deviceToken:\(token))
Messaging.messaging()。apnsToken = deviceToken
debugPrint(Firebase Token:,InstanceID.instanceID()。 token()as Any)
}

func messaging(_ messaging:Messaging,didReceive remoteMessage:MessagingRemoteMessage)
{
debugPrint(---> messaging :\(messaging))
debugPrint(---> didReceive Remote Message:\(remoteMessage.appData))
guard let data =
试试? JSONSerialization.data(withJSONObject:remoteMessage.appData,options:.prettyPrinted),
let prettyPrinted = String(data:data,encoding:.utf8)else {return}
print(Received received channel message: \ n \(prettyPrinted))
}

几条警告日志消失了,

  2017-06-01 17:40:12.897916-0400我在前台和后台执行测试lol [8275:2217196] [Firebase / Messaging] [I-FCM002019] FIRMessaging接收到的数据消息,但FIRMessagingDelegate的消息传递:didReceiveMessage:未执行
2017-06-01 17:40:12.898 lol [8275]< ;警告> [Firebase / Messaging] [I-FCM002019] FIRMessaging收到的数据消息,但FIRMessagingDelegate的消息传递:didReceiveMessage:未实现
###> 1.2 AppDelegate DidEnterBackground
2017-06-01 17: 40:29.943006-0400大声笑[8275:2217037]无法指示服务com.apple.WebKit.WebContent:113:找不到指定的服务
2017-06-01 17:40:29.944689-0400大声笑[8275: 2217037] Could not signal service com.apple.WebKit.Networking:113:找不到指定的服务
2017-06-01 17:40:30.000428-0400 lol [8275:2217203] dnssd_clientstub read_all(27)DEFUNCT
###> 1.3 AppDelegate DidBecomeActive
2017-06-01 17:40:30.760941-0400 FIRM将接收到的数据消息传递给消息队列[8275:2217443] [Firebase / Messaging] [I-FCM002019] ,但FIRMessagingDelegate的消息:didReceiveMessage:未执行
2017-06-01 17:40:30.761 lol [8275]< Warning> [Firebase / Messaging] [I-FCM002019] FIRMessaging收到的数据消息,但FIRMessagingDelegate的消息传递:didReceiveMessage:未实现

我试过这个,但它仍然显示这些日志,它不显示任何通知:
< a href =https://i.stack.imgur.com/yNwzB.png =nofollow noreferrer>



是我失踪的东西吗?

解决方案

您需要在Cloud Messaging中将推送通知证书添加到FCM控制台。只有这样它才能将通知发送到您的应用程序。此外,请确保您在iOS应用的功能中启用了推送通知。



更新
$注册Firebase通知
func configureFirebase(application:UIApplication){

FirebaseApp.configure()

Messaging.messaging()。delegate = self

//注册远程通知。这显示了第一次运行的权限对话框,
//在更合适的时间显示对话框,相应地移动这个注册。
// [START register_for_notifications]
if #available(iOS 10.0,*){
//对于iOS 10显示通知(通过APNS发送)
UNUserNotificationCenter.current()。 delegate = self

let authOptions:UNAuthorizationOptions = [.alert,.badge,.sound]
UNUserNotificationCenter.current()。requestAuthorization(
options:authOptions,
完成处理程序:{_,_in})
} else {
设置:UIUserNotificationSettings =
UIUserNotificationSettings(类型:[.alert,.badge,.sound],类别:nil)
application.registerUserNotificationSettings(settings)
}

application.registerForRemoteNotifications()


print(----- firebase token:\\ \\(String(描述:Messaging.messaging()。fcmToken))----)


}


// MARK: FCM令牌刷新
func消息(_消息:消息,didRefreshRegi strationToken fcmToken:String){
// FCM令牌更新,在后台服务器上更新
}


func消息传递(_ messaging:Messaging,didReceive remoteMessage:MessagingRemoteMessage ){
print(remoteMessage:\(remoteMessage))
}

//当通知传送到前台应用程序时调用。
@available(iOS 10.0,*)
func userNotificationCenter(_ center:UNUserNotificationCenter,willPresent notification:UNNotification,withCompletionHandler completionHandler:@escaping(UNNotificationPresentationOptions) - > Void){
completionHandler .alert,.badge,.sound])
}

//调用以让您的应用程序知道用户为给定通知选择了哪个操作。
@available(iOS 10.0,*)
func userNotificationCenter(_ center:UNUserNotificationCenter,didReceive response:UNNotificationResponse,withCompletionHandler completionHandler:@escaping() - > Void){
print(User Info = \(response.notification.request.content.userInfo))

completionHandler()
}
}



内部调用 configureFirebase(application:) didFinishLaunchingWithOptions 你的 AppDelegate

I'm working on Xcode 8.3.2 for iOS 10.3.2 with Swift 3, my project use firebase cloud messaging, when my p12 certificates expired, I updated my certificates p12 to p8 as suggested Firebase's documentation, but the push notifications stopped coming, yesterday when I used the console firebase to test, it was working but today no, the logs print me this as normal:

2017-05-30 10:13:23.932066-0400 lol[5576:1530669] WARNING: Firebase Analytics App Delegate Proxy is disabled. To log deep link campaigns manually, call the methods in FIRAnalytics+AppDelegate.h.
2017-05-30 10:13:23.949512-0400 lol[5576:1530669] 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
2017-05-30 10:13:24.368364-0400 lol[5576:1530669] [Crashlytics] Version 3.8.2 (118)
2017-05-30 10:13:24.397942-0400 lol[5576:1530669] [MC] System group container for systemgroup.com.apple.configurationprofiles path is /private/var/containers/Shared/SystemGroup/systemgroup.com.apple.configurationprofiles
2017-05-30 10:13:24.398433-0400 lol[5576:1530669] [MC] Reading from public effective user settings.
initializeFCM
Notification access accepted.
2017-05-30 10:13:24.679: <FIRInstanceID/WARNING> Failed to fetch APNS token Error Domain=com.firebase.iid Code=1001 "(null)"
2017-05-30 10:13:24.681: <FIRMessaging/INFO> FIRMessaging library version 1.2.0
2017-05-30 10:13:24.683213-0400 lol[5576:1530706] [Firebase/Crash][I-CRA000004] Successfully initialized
2017-05-30 10:13:24.683 lol[5576] <Notice> [Firebase/Crash][I-CRA000004] Successfully initialized
2017-05-30 10:13:24.685110-0400 lol[5576:1530706] <FIRAnalytics/INFO> Firebase Analytics v.3600000 started
2017-05-30 10:13:24.685 lol[5576:] <FIRAnalytics/INFO> Firebase Analytics v.3600000 started
2017-05-30 10:13:24.685438-0400 lol[5576:1530706] <FIRAnalytics/INFO> To enable debug logging set the following application argument: -FIRAnalyticsDebugEnabled
2017-05-30 10:13:24.685 lol[5576:] <FIRAnalytics/INFO> To enable debug logging set the following application argument: -FIRAnalyticsDebugEnabled
"GCM TOKEN = Optional(\"it's working: PLEASE HELP STACKOVERFLOW\")"
"didRegisterForRemoteNotificationsWithDeviceToken: DATA"
"*** deviceToken: <66666666 it's working: PLEASE HELP STACKOVERFLOW 99999999>"
2017-05-30 10:13:24.837: <FIRInstanceID/WARNING> APNS Environment in profile: development
"Firebase Token:" Optional("it's working: PLEASE HELP STACKOVERFLOW")
2017-05-30 10:13:24.932076-0400 lol[5576:1530727] <FIRAnalytics/INFO> Firebase Analytics enabled
2017-05-30 10:13:24.932 lol[5576:] <FIRAnalytics/INFO> Firebase Analytics enabled
"Connected to FCM."

the new strange log is:

2017-05-30 10:13:24.679: <FIRInstanceID/WARNING> Failed to fetch APNS token Error Domain=com.firebase.iid Code=1001 "(null)"

my code is:

//
//  AppDelegate.swift
//  lol
//
//  Created by Dennis Mostajo on 06/06/16. ---> 666 the number of the beast! O_O!
//  Copyright © 2016 Dennis Mostajo. All rights reserved.
//

import UIKit

import FirebaseAnalytics
import FirebaseInstanceID
import FirebaseMessaging
import UserNotifications

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {

    var window: UIWindow?


    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool
    {
        // Override point for customization after application launch.
         self.initializeFCM(application)
        let token = FIRInstanceID.instanceID().token()
        debugPrint("GCM TOKEN = \(String(describing: token))")
        return true
    }

    func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error)
    {
        debugPrint("didFailToRegisterForRemoteNotificationsWithError: \(error)")
    }

    func applicationReceivedRemoteMessage(_ remoteMessage: FIRMessagingRemoteMessage)
    {
        debugPrint("remoteMessage:\(remoteMessage.appData)")
    }

    func initializeFCM(_ application: UIApplication)
    {
        print("initializeFCM")
        //-------------------------------------------------------------------------//
        if #available(iOS 10.0, *) // enable new way for notifications on iOS 10
        {
            let center = UNUserNotificationCenter.current()
            center.delegate = self
            center.requestAuthorization(options: [.badge, .alert , .sound]) { (accepted, error) in
                if !accepted
                {
                    print("Notification access denied.")
                }
                else
                {
                    print("Notification access accepted.")
                    UIApplication.shared.registerForRemoteNotifications();
                }
            }
        }
        else
        {
            let type: UIUserNotificationType = [UIUserNotificationType.badge, UIUserNotificationType.alert, UIUserNotificationType.sound];
            let setting = UIUserNotificationSettings(types: type, categories: nil);
            UIApplication.shared.registerUserNotificationSettings(setting);
            UIApplication.shared.registerForRemoteNotifications();
        }

        FIRApp.configure()

        NotificationCenter.default.addObserver(self, selector: #selector(self.tokenRefreshNotificaiton),
                                               name: NSNotification.Name.firInstanceIDTokenRefresh, object: nil)
    }

    func registrationhandler(_ registrationToken: String!, error: NSError!)
    {
        if (registrationToken != nil)
        {
          debugPrint("registrationToken = \(String(describing: registrationToken))")
        }
        else
        {
            debugPrint("Registration to GCM failed with error: \(error.localizedDescription)")
        }
    }

    func tokenRefreshNotificaiton(_ notification: Foundation.Notification)
    {
        if let refreshedToken = FIRInstanceID.instanceID().token()
        {
            debugPrint("InstanceID token: \(refreshedToken)")
        }
        connectToFcm()
    }

    func connectToFcm()
    {
        // Won't connect since there is no token
        guard FIRInstanceID.instanceID().token() != nil else
        {
            return;
        }
        // Disconnect previous FCM connection if it exists.
        FIRMessaging.messaging().disconnect()
        FIRMessaging.messaging().connect { (error) in
            if (error != nil)
            {
                debugPrint("Unable to connect with FCM. \(String(describing: error))")
            }
            else
            {
                debugPrint("Connected to FCM.")
            }
        }
    }

    func application(_ application: UIApplication, didRegister notificationSettings: UIUserNotificationSettings)
    {
        debugPrint("didRegister notificationSettings")
        if (notificationSettings.types == .alert || notificationSettings.types == .badge || notificationSettings.types == .sound)
        {
            application.registerForRemoteNotifications()
        }
    }

    func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData)
    {
        debugPrint("didRegisterForRemoteNotificationsWithDeviceToken: NSDATA")

        let token = String(format: "%@", deviceToken as CVarArg)
        debugPrint("*** deviceToken: \(token)")
        #if RELEASE_VERSION
            FIRInstanceID.instanceID().setAPNSToken(deviceToken as Data, type:FIRInstanceIDAPNSTokenType.prod)
        #else
            FIRInstanceID.instanceID().setAPNSToken(deviceToken as Data, type:FIRInstanceIDAPNSTokenType.sandbox)
        #endif
        debugPrint("Firebase Token:",FIRInstanceID.instanceID().token() as Any)
    }

    @available(iOS 10.0, *)
    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void)
    {
        //Handle the notification ON APP foreground
        debugPrint("*** willPresent notification")
        debugPrint("*** notification: \(notification)")
    }

    @available(iOS 10.0, *)
    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void)
    {
        //Handle the notification ON BACKGROUND
        debugPrint("*** didReceive response Notification ")
        debugPrint("*** response: \(response)")
    }

    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data)
    {
        debugPrint("didRegisterForRemoteNotificationsWithDeviceToken: DATA")
        let token = String(format: "%@", deviceToken as CVarArg)
        debugPrint("*** deviceToken: \(token)")
        #if RELEASE_VERSION
            FIRInstanceID.instanceID().setAPNSToken(deviceToken as Data, type:FIRInstanceIDAPNSTokenType.prod)
        #else
            FIRInstanceID.instanceID().setAPNSToken(deviceToken as Data, type:FIRInstanceIDAPNSTokenType.sandbox)
        #endif
        debugPrint("Firebase Token:",FIRInstanceID.instanceID().token() as Any)
    }

    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any],
                     fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
        // 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
        FIRMessaging.messaging().appDidReceiveMessage(userInfo)

        if let messageID = userInfo["gcm.message_id"] {
            debugPrint("Message ID: \(messageID)")
        }
        debugPrint("*** userInfo: \(userInfo)")


        // Print full message.
        completionHandler(.newData)
    }

    func application(_ application: UIApplication, didReceive notification: UILocalNotification)
    {
        if application.applicationState != UIApplicationState.active
        {
            if let gcmMessageType = GCMMessageType(rawValue: notificationType)
            {
                debugPrint("didReceiveLocalNotification")
                debugPrint("notification:\(notification)")
            }
        }
        //application.applicationIconBadgeNumber = 0
    }


    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.
        connectToFcm()
    }

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

I have made some mistake ?, or I need to configure something ?, something more that should increase for the difference between iOS 9 and iOS 10.3, or add to firebase settings, thanks a lot for any help

//------------------------------------------------------------------------------------------------------------------------------//

EDIT:

Hi again, well I have updated Firebase to the latest version 4.0.0, doing these updates in my code:

  func initializeFCM(_ application: UIApplication)
    {
        print("initializeFCM")
      //-------------------------------------------------------------------------//
        if #available(iOS 10.0, *) // enable new way for notifications on iOS 10
        {
            let center = UNUserNotificationCenter.current()
            center.delegate = self
            center.requestAuthorization(options: [.badge, .alert , .sound]) { (accepted, error) in
                if !accepted
                {
                    print("Notification access denied.")
                }
                else
                {
                    print("Notification access accepted.")
                    UIApplication.shared.registerForRemoteNotifications();
                }
            }
        }
        else
        {
            let type: UIUserNotificationType = [UIUserNotificationType.badge, UIUserNotificationType.alert, UIUserNotificationType.sound];
            let setting = UIUserNotificationSettings(types: type, categories: nil);
            UIApplication.shared.registerUserNotificationSettings(setting);
            UIApplication.shared.registerForRemoteNotifications();
        }
      //-------------------------------------------------------------------------//

        FirebaseApp.configure()
        Messaging.messaging().shouldEstablishDirectChannel = true

        NotificationCenter.default.addObserver(self, selector: #selector(self.tokenRefreshNotificaiton),
                                                         name: NSNotification.Name.InstanceIDTokenRefresh, object: nil)
    }

 func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData)
    {
        debugPrint("didRegisterForRemoteNotificationsWithDeviceToken: NSDATA")

        let token = String(format: "%@", deviceToken as CVarArg)
        debugPrint("*** deviceToken: \(token)")
        Messaging.messaging().apnsToken = deviceToken as Data
        debugPrint("Firebase Token:",InstanceID.instanceID().token() as Any)
    }

    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data)
    {
        debugPrint("didRegisterForRemoteNotificationsWithDeviceToken: DATA")
        let token = String(format: "%@", deviceToken as CVarArg)
        debugPrint("*** deviceToken: \(token)")
        Messaging.messaging().apnsToken = deviceToken
        debugPrint("Firebase Token:",InstanceID.instanceID().token() as Any)
    }

func messaging(_ messaging: Messaging, didReceive remoteMessage: MessagingRemoteMessage)
    {
        debugPrint("--->messaging:\(messaging)")
        debugPrint("--->didReceive Remote Message:\(remoteMessage.appData)")
        guard let data =
            try? JSONSerialization.data(withJSONObject: remoteMessage.appData, options: .prettyPrinted),
            let prettyPrinted = String(data: data, encoding: .utf8) else { return }
        print("Received direct channel message:\n\(prettyPrinted)")
    }

Several warnings logs disappeared but when I do the test in foreground and background way this logs print me:

2017-06-01 17:40:12.897916-0400 lol[8275:2217196] [Firebase/Messaging][I-FCM002019] FIRMessaging received data-message, but FIRMessagingDelegate's-messaging:didReceiveMessage: not implemented
2017-06-01 17:40:12.898 lol[8275] <Warning> [Firebase/Messaging][I-FCM002019] FIRMessaging received data-message, but FIRMessagingDelegate's-messaging:didReceiveMessage: not implemented
"###> 1.2 AppDelegate DidEnterBackground"
2017-06-01 17:40:29.943006-0400 lol[8275:2217037] Could not signal service com.apple.WebKit.WebContent: 113: Could not find specified service
2017-06-01 17:40:29.944689-0400 lol[8275:2217037] Could not signal service com.apple.WebKit.Networking: 113: Could not find specified service
2017-06-01 17:40:30.000428-0400 lol[8275:2217203] dnssd_clientstub read_all(27) DEFUNCT
"###> 1.3 AppDelegate DidBecomeActive"
2017-06-01 17:40:30.760941-0400 lol[8275:2217443] [Firebase/Messaging][I-FCM002019] FIRMessaging received data-message, but FIRMessagingDelegate's-messaging:didReceiveMessage: not implemented
2017-06-01 17:40:30.761 lol[8275] <Warning> [Firebase/Messaging][I-FCM002019] FIRMessaging received data-message, but FIRMessagingDelegate's-messaging:didReceiveMessage: not implemented

I tried this but it still shows those logs and it does not show any notifications:

is anything I'm missing?, Thanks for the answers!!

解决方案

You need to add Push notification certificate to FCM Console in Cloud Messaging. Only then It'll be able to send notifications to your App. Also, make sure you've enabled Push notifications in Capabilities in your iOS App.

Update:

extension AppDelegate: MessagingDelegate {
// Registering for Firebase notifications
func configureFirebase(application: UIApplication) {

    FirebaseApp.configure()

    Messaging.messaging().delegate = self

    // Register for remote notifications. This shows a permission dialog on first run, to
    // show the dialog at a more appropriate time move this registration accordingly.
    // [START register_for_notifications]
    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 })
    } else {
        let settings: UIUserNotificationSettings =
            UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
        application.registerUserNotificationSettings(settings)
    }

    application.registerForRemoteNotifications()


    print("-----firebase token: \(String(describing: Messaging.messaging().fcmToken)) ----")


}


//MARK: FCM Token Refreshed
func messaging(_ messaging: Messaging, didRefreshRegistrationToken fcmToken: String) {
    // FCM token updated, update it on Backend Server
}


func messaging(_ messaging: Messaging, didReceive remoteMessage: MessagingRemoteMessage) {
        print("remoteMessage: \(remoteMessage)")
}

//Called when a notification is delivered to a foreground app.
@available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
    completionHandler([.alert, .badge, .sound])
}

//Called to let your app know which action was selected by the user for a given notification.
@available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
    print("User Info = \(response.notification.request.content.userInfo)")

    completionHandler()
}
}

Call configureFirebase(application:) inside didFinishLaunchingWithOptions of your AppDelegate.

这篇关于Firebase在Xcode 8.3上发布iOS 10.3 Swift 3 FCM通知无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆