ios10,Swift 3和Firebase推送通知(FCM) [英] ios10, Swift 3 and Firebase Push Notifications (FCM)

查看:213
本文介绍了ios10,Swift 3和Firebase推送通知(FCM)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在努力显示我从FCM通知控制台发送给我的设备的推送通知。我可以看到设备正在接收通知,因为我可以看到我发送的消息test8。

 连接到FCM。 
%@ [AnyHashable(notification):{
body = test8;
e = 1;
},

但是,如果我的应用程序处于前台或后台,并不重要不要显示通知。

我在info.plist中添加了所需的后台模式 - 应用程序下载内容以响应推送通知。我的证书是正确的,我没有问题生成一个令牌。

 导入UIKit 
导入UserNotifications
导入Firebase
导入FirebaseInstanceID
导入FirebaseMessaging

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

var window:UIWindow?

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

// [START register_for_notifications]
if #available(iOS 10.0,*){
let authOptions:UNAuthorizationOptions = [.Alert,.Badge,.Sound]
UNUserNotificationCenter.currentNotificationCenter()。requestAuthorizationWithOptions(
authOptions,
completionHandler:{_,_in})

//对于iOS 10显示通知(通过APNS发送)
UNUserNotificationCenter.currentNotificationCenter()。delegate = self
//对于iOS 10数据消息(通过FCM发送)
FIRMessaging.messaging()。remoteMessageDelegate = self

} else {
设置:UIUserNotificationSettings =
UIUserNotificationSettings(forTypes:[.Alert,.Badge,.Sound],类别:nil)
application.registerUserNotificationSettings(设置)
应用程序.registerForRemoteNotifications()
}

application.registerForRemoteNotifications()

// [END register_for_notifications]

FIRApp.configure()

/ /为InstanceID令牌刷新回调添加观察者。
NSNotificationCenter.defaultCenter()。addObserver(self,
selector:#selector(self.tokenRefreshNotification),
name:kFIRInstanceIDTokenRefreshNotification,
object:nil)

$ true

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

//打印消息ID。
print(Message ID:\(userInfo [gcm.message_id]!))

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

// [START refresh_token]
func tokenRefreshNotification(notification :NSNotification){
if refreshedToken = FIRInstanceID.instanceID()。token(){
print(InstanceID token:\(refreshedToken))
}

//连接到FCM,因为在拥有令牌之前尝试连接可能失败。
connectToFcm()
}
// [END refresh_token]

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

func applicationDidBecomeActive(application :UIApplication){
connectToFcm()
}

// [START disconnect_from_fcm]
func applicationDidEnterBackground(application:UIApplication){
FIRMessaging.messaging ).disconnect()
print(与FCM断开连接)

// [END disconnect_from_fcm]
}

// [START ios_10_message_handling]
@available(iOS 10,*)
扩展名AppDelegate:UNUserNotificationCenterDelegate {

//接收iOS 10设备显示的通知。
func userNotificationCenter(center:UNUserNotificationCenter,
willPresentNotification notification:UNNotification,
withCompletionHandler completionHandler:(UNNotificationPresentationOptions) - > Void){
let userInfo = notification.request.content.userInfo
//打印消息ID。
print(Message ID:\(userInfo [gcm.message_id]!))
//打印完整的信息。
print(%@,userInfo)
}
}
$ b extension AppDelegate:FIRMessagingDelegate {
//在iOS 10设备上接收数据信息。
func applicationReceivedRemoteMessage(remoteMessage:FIRMessagingRemoteMessage){
print(%@,remoteMessage.appData)
}
}
// [END ios_10_message_handling]

我一直在试图自己研究和解决这个问题,但是我遇到了问题。任何帮助或建议,将不胜感激。解决方案内部方法 didRegisterForRemoteNotificationsWithDeviceToken ,添加以下代码:

$ p $ func application(application:UIApplication,didRegisterForRemoteNotificationsWithDeviceToken deviceToken:NSData){
let tokenChars = UnsafePointer< CChar>(deviceToken .bytes)
var tokenString =

for i in 0 ..< deviceToken.length {
tokenString + = String(format:%02.2hhx,arguments :[tokenChars [i]])
}

FIRInstanceID.instanceID()。setAPNSToken(deviceToken,type:FIRInstanceIDAPNSTokenType.Unknown)

print(tokenString: \(tokenString))
}

不要忘记启用推送通知功能内。


I am struggling to display my push notifications that I am sending to my device from the FCM notification console. I can see the device is receiving the notification because I can see the message I send "test8"

Connected to FCM.
%@ [AnyHashable("notification"): {
    body = test8;
    e = 1;
},

But it does not matter if my app is in the foreground or background I don't get the notification displayed.

I have added "Required background modes - App downloads content in response to push notifications" to the info.plist. My certificates are correct and I have no issue generating a token. My app is receiving the notifications but just not displaying them.

import UIKit
import UserNotifications
import Firebase
import FirebaseInstanceID
import FirebaseMessaging

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

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

        // [START register_for_notifications]
        if #available(iOS 10.0, *) {
            let authOptions : UNAuthorizationOptions = [.Alert, .Badge, .Sound]
            UNUserNotificationCenter.currentNotificationCenter().requestAuthorizationWithOptions(
                authOptions,
                completionHandler: {_,_ in })

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

        } else {
            let settings: UIUserNotificationSettings =
                UIUserNotificationSettings(forTypes: [.Alert, .Badge, .Sound], categories: nil)
            application.registerUserNotificationSettings(settings)
            application.registerForRemoteNotifications()
        }

        application.registerForRemoteNotifications()

        // [END register_for_notifications]

        FIRApp.configure()

        // Add observer for InstanceID token refresh callback.
        NSNotificationCenter.defaultCenter().addObserver(self,
                                                         selector: #selector(self.tokenRefreshNotification),
                                                         name: kFIRInstanceIDTokenRefreshNotification,
                                                         object: nil)

        return true
    }

    // [START receive_message]
    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("Message ID: \(userInfo["gcm.message_id"]!)")

        // Print full message.
        print("%@", userInfo)
    }
    // [END receive_message]

    // [START refresh_token]
    func tokenRefreshNotification(notification: NSNotification) {
        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()
    }
    // [END refresh_token]

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

    func applicationDidBecomeActive(application: UIApplication) {
        connectToFcm()
    }

    // [START disconnect_from_fcm]
    func applicationDidEnterBackground(application: UIApplication) {
        FIRMessaging.messaging().disconnect()
        print("Disconnected from FCM.")
    }
    // [END disconnect_from_fcm]
}

// [START ios_10_message_handling]
@available(iOS 10, *)
extension AppDelegate : UNUserNotificationCenterDelegate {

    // Receive displayed notifications for iOS 10 devices.
    func userNotificationCenter(center: UNUserNotificationCenter,
                                willPresentNotification notification: UNNotification,
                                withCompletionHandler completionHandler: (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)
    }
}
// [END ios_10_message_handling]

I having been trying to research and solve this issue on my own but I am having issues. Any help or suggestions would be greatly appreciated.

解决方案

Inside method didRegisterForRemoteNotificationsWithDeviceToken, add the following code:

func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
    let tokenChars = UnsafePointer<CChar>(deviceToken.bytes)
    var tokenString = ""

    for i in 0..<deviceToken.length {
        tokenString += String(format: "%02.2hhx", arguments: [tokenChars[i]])
    }

    FIRInstanceID.instanceID().setAPNSToken(deviceToken, type: FIRInstanceIDAPNSTokenType.Unknown)

    print("tokenString: \(tokenString)")
}

And do not forget to enable Push Notifications inside Capabilities.

这篇关于ios10,Swift 3和Firebase推送通知(FCM)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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