Firebase云消息传递不会创建推送通知,但会获取信息 [英] Firebase Cloud Messaging Doesn't Create Push Notifications but Gets Information

查看:155
本文介绍了Firebase云消息传递不会创建推送通知,但会获取信息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在完成本教程( https://www.youtube.com/watch?v = JsWHzU1DxjM )尝试把推送通知到我的iOS应用程序。我能够成功获取APNS的证书,并设置推送通知和后台模式功能。此外,当我从Firebase控制台发送一条通知时,Firebase能够从通知中获取信息。但是,当应用程序在后台运行时,横幅通知不会出现。我觉得我可能有一个问题转换从Objective-C到Swift的教程,因为该教程是在Objective-C,但我不知道。如果有帮助,我把我的AppDelegate类和程序输出。

  @UIApplicationMain $ b $ class AppDelegate:UIResponder,UIApplicationDelegate {

var window:UIWindow?

func application(application:UIApplication,didFinishLaunchingWithOptions launchOptions:[NSObject:AnyObject]?) - > Bool {

connectToFcm()

NSNotificationCenter.defaultCenter()。addObserver(
self,
选择器:#selector(tokenRefreshCallback),
name:kFIRInstanceIDTokenRefreshNotification,
object:nil)

let allNotificationTypes = UIUserNotificationType(arrayLiteral:UIUserNotificationType.Sound,UIUserNotificationType.Alert,UIUserNotificationType.Badge)
let settings = UIUserNotificationSettings(forTypes :allNotificationTypes,categories:nil)
application.registerUserNotificationSettings(settings)
application.registerForRemoteNotifications()
return FBSDKApplicationDelegate.sharedInstance()。application(application,didFinishLaunchingWithOptions:launchOptions)
}

func application(application:UIApplication,openURL url:NSURL,sourceApplication:String?,annotation:AnyObject) - > Bool {
return FBSDKApplicationDelegate.sharedInstance()。application(application,openURL:url,sourceApplication:sourceApplication,annotation:annotation)
}
$ b $ override init(){
FIRApp.configure()
FIRDatabase.database()。persistenceEnabled = false
}

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

$ b $ func applicationDidEnterBackground(application:UIApplication){
//使用此方法释放共享资源,保存用户数据,使计时器无效并存储足够的应用程序状态信息你的应用程序到当前的状态,以防以后终止。
FIRMessaging.messaging()。disconnect()
print(与FCM断开连接)
//如果您的应用程序支持后台执行,则调用此方法而不是applicationWillTerminate:退出。


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

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

func applicationWillTerminate(application:UIApplication){
// try! FIRAuth.auth()!. signOut()
}

func connectToFcm(){
FIRMessaging.messaging()。connectWithCompletion {(error)in
if错误!=无){
print(无法连接FCM。\(错误))
} else {
print(Connected to FCM。)
}



$ b func tokenRefreshCallback(notification:NSNotification){
let refreshedToken = FIRInstanceID.instanceID()。token()
print(InstanceID token:\(refreshedToken))

//连接到FCM,因为连接可能在拥有令牌之前尝试失败。
if(refreshedToken!= nil)
{
connectToFcm()
}

}

func application(application: UIApplication,didReceiveRemoteNotification userInfo:[NSObject:AnyObject],
fetchCompletionHandler completionHandler:(UIBackgroundFetchResult) - > Void){
//如果在应用程序处于后台时收到通知消息,则
//直到用户点击启动应用程序的通知,这个回调才会被触发。
// TODO:处理通知数据

//打印消息ID。
print(\(userInfo))
// print(Message ID:\(userInfo [gcm.message_id]!))
NSNotificationCenter.defaultCenter() .postNotificationName(name,object:userInfo)

//打印完整的信息。
print(%@,userInfo)
}
}

控制台日志:

  2016-06-20 19:14:50.801 MapKitTry [2244:721460]配置默认的应用程序。 
2016-06-20 19:14:50.839 MapKitTry [2244:]< FIRAnalytics / INFO> Firebase Analytics v.3200000开始
2016-06-20 19:14:50.846 MapKitTry [2244:]< FIRAnalytics / INFO>要启用调试日志记录,请设置以下应用程序参数:-FIRAnalyticsDebugEnabled(请参阅-omitted-)
2016-06-20 19:14:50.849:< FIRInstanceID / WARNING> FIRInstanceID启用了AppDelegate代理,将swizzle应用程序委托给远程通知处理程序。要禁用将FirebaseAppDelegateProxyEnabled添加到Info.plist并将其设置为NO
2016-06-20 19:14:50.849:< FIRInstanceID / WARNING>无法获取APNS令牌Error Domain = com.firebase.iid Code = 1001(null)
2016-06-20 19:14:50.853:< FIRMessaging / INFO> FIRMessaging库版本1.1.0
2016-06-20 19:14:50.863:< FIRMessaging / WARNING> FIRMessaging启用AppDelegate代理,将swizzle app委托给远程通知接收处理程序。添加FirebaseAppDelegateProxyEnabled到你的Info.plist并设置为NO
2016-06-20 19:14:50.902 MapKitTry [2244:]< FIRAnalytics / INFO>成功自动创建Firebase Analytics应用程序委托代理。要禁用代理,请在Info.plist中设置标志FirebaseAppDelegateProxyEnabled为NO
no login
2016-06-20 19:14:51.076 MapKitTry [2244:]< FIRAnalytics / INFO>已启用Firebase Analytics
已连接到FCM。
[通知:{
body =推送通知;
e = 1;
},collapse_key:pdrum3.KingOfTheTown,from:302278087187]
%@ [通知:{
body =推送通知;
e = 1;
},collapse_key:pdrum3.KingOfTheTown,from:302278087187]


解决方案在您的info.plist中添加 FirebaseAppDelegateProxyEnabled 键入布尔值NO。

< img src =https://i.stack.imgur.com/XnMm0.pngalt =info.plist-image>


I was working through this tutorial (https://www.youtube.com/watch?v=JsWHzU1DxjM) to try and put push notifications into my iOS app. I was able to successfully get the certificate for APNS and set the "push notification" and "background modes" capabilities to on. Also, Firebase is able to get the info from the notification when I send one from the firebase console. However, when the app is running in the background the banner notifications never appear. I feel like I may have had a problem converting the tutorial from Objective-C to Swift because the tutorial was in Objective-C, but I'm not sure. I put my AppDelegate class and the program output if that helps at all. I would really appreciate any help.

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

var window: UIWindow?

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {

    connectToFcm()

    NSNotificationCenter.defaultCenter().addObserver(
        self,
        selector: #selector(tokenRefreshCallback),
        name: kFIRInstanceIDTokenRefreshNotification,
        object: nil)

    let allNotificationTypes = UIUserNotificationType(arrayLiteral: UIUserNotificationType.Sound, UIUserNotificationType.Alert, UIUserNotificationType.Badge)
    let settings = UIUserNotificationSettings(forTypes: allNotificationTypes, categories: nil)
    application.registerUserNotificationSettings(settings)
    application.registerForRemoteNotifications()
    return FBSDKApplicationDelegate.sharedInstance().application(application, didFinishLaunchingWithOptions: launchOptions)
}

func application(application: UIApplication, openURL url: NSURL, sourceApplication: String?, annotation: AnyObject) -> Bool {
    return FBSDKApplicationDelegate.sharedInstance().application(application, openURL: url, sourceApplication: sourceApplication, annotation: annotation)
}

override init() {
    FIRApp.configure()
    FIRDatabase.database().persistenceEnabled = false
}

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 throttle down OpenGL ES frame rates. 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.
    FIRMessaging.messaging().disconnect()
    print("Disconnected from FCM.")
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

func applicationWillEnterForeground(application: UIApplication) {
    connectToFcm()
    // Called as part of the transition from the background to the inactive 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) {
    //try! FIRAuth.auth()!.signOut()
}

func connectToFcm() {
    FIRMessaging.messaging().connectWithCompletion { (error) in
        if (error != nil) {
            print("Unable to connect with FCM. \(error)")
        } else {
            print("Connected to FCM.")
        }
    }
}


func tokenRefreshCallback(notification: NSNotification) {
    let refreshedToken = FIRInstanceID.instanceID().token()
    print("InstanceID token: \(refreshedToken)")

    // Connect to FCM since connection may have failed when attempted before having a token.
    if (refreshedToken != nil)
    {
        connectToFcm()
    }

    }

func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject],
                 fetchCompletionHandler completionHandler: (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

    // Print message ID.
    print("\(userInfo)")
    //print("Message ID: \(userInfo["gcm.message_id"]!)")
    NSNotificationCenter.defaultCenter().postNotificationName("name", object: userInfo)

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

Console log:

2016-06-20 19:14:50.801 MapKitTry[2244:721460] Configuring the default app.
2016-06-20 19:14:50.839 MapKitTry[2244:] <FIRAnalytics/INFO> Firebase Analytics v.3200000 started
2016-06-20 19:14:50.846 MapKitTry[2244:] <FIRAnalytics/INFO> To enable debug logging set the following application argument: -FIRAnalyticsDebugEnabled (see -omitted-)
2016-06-20 19:14:50.849: <FIRInstanceID/WARNING> FIRInstanceID AppDelegate proxy enabled, will swizzle app delegate remote notification handlers. To disable add "FirebaseAppDelegateProxyEnabled" to your Info.plist and set it to NO
2016-06-20 19:14:50.849: <FIRInstanceID/WARNING> Failed to fetch APNS token Error Domain=com.firebase.iid Code=1001 "(null)"
2016-06-20 19:14:50.853: <FIRMessaging/INFO> FIRMessaging library version 1.1.0
2016-06-20 19:14:50.863: <FIRMessaging/WARNING> FIRMessaging AppDelegate proxy enabled, will swizzle app delegate remote notification receiver handlers. Add "FirebaseAppDelegateProxyEnabled" to your Info.plist and set it to NO
2016-06-20 19:14:50.902 MapKitTry[2244:] <FIRAnalytics/INFO> Successfully created Firebase Analytics App Delegate Proxy automatically. To disable the proxy, set the flag FirebaseAppDelegateProxyEnabled to NO in the Info.plist
no login
2016-06-20 19:14:51.076 MapKitTry[2244:] <FIRAnalytics/INFO> Firebase Analytics enabled
Connected to FCM.
[notification: {
body = "Push notification";
e = 1;
}, collapse_key: pdrum3.KingOfTheTown, from: 302278087187]
%@ [notification: {
body = "Push notification";
e = 1;
}, collapse_key: pdrum3.KingOfTheTown, from: 302278087187]

解决方案

Add FirebaseAppDelegateProxyEnabled type "Boolean" value "NO" in your info.plist:

这篇关于Firebase云消息传递不会创建推送通知,但会获取信息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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