FCM功能 - Recive通知

时间:2017-12-06 22:37:29

标签: json swift firebase-cloud-messaging google-cloud-functions

我正在开发一个社交网络应用,用户可以一起关注/取消关注。当X跟随A像instagram一样时,如何从firebase云功能接收通知?

我在firebase上部署了我的index.js

my index.js codes

我的项目Appdelegate:

import UIKit
import Firebase
import UserNotifications

   @UIApplicationMain
 class AppDelegate: UIResponder, 
UIApplicationDelegate,UNUserNotificationCenterDelegate, 
MessagingDelegate {
 func messaging(_ messaging: Messaging, didRefreshRegistrationToken 
 fcmToken: String) {
    print("Firebase registration token: \(fcmToken)")
}


var window: UIWindow?


func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

    UITabBar.appearance().tintColor = .white


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


    FirebaseApp.configure()

    let token = Messaging.messaging().fcmToken
    print("FCM token: \(token ?? "")")

    return true

}




func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
    var token = ""
    for i in 0..<deviceToken.count {
        token = token + String(format: "%02.2hhx", arguments: [deviceToken[i]])
    }
    print("Registration succeeded! Token: ", token)
}

func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
    print("Registration failed!")
}





func application(_ application: UIApplication,didReceiveRemoteNotification notification: [AnyHashable:Any],fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
    if Auth.auth().canHandleNotification(notification){
        completionHandler(UIBackgroundFetchResult.noData)
    }

    // This notification is not auth related, developer should handle it.
}

func applicationDidBecomeActive(_ application: UIApplication) {

    //YFVolumeView.current.updateActiveState()
}


// Firebase notification received
@available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter,  willPresent notification: UNNotification, withCompletionHandler   completionHandler: @escaping (_ options:   UNNotificationPresentationOptions) -> Void) {

    // custom code to handle push while app is in the foreground
    print("Handle push from foreground\(notification.request.content.userInfo)")

    let dict = notification.request.content.userInfo["aps"] as! NSDictionary
    let d : [String : Any] = dict["alert"] as! [String : Any]
    let body : String = d["body"] as! String
    let title : String = d["title"] as! String
    print("Title:\(title) + body:\(body)")
    self.showAlertAppDelegate(title: title,message:body,buttonTitle:"ok",window:self.window!)

}

@available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
    // if you set a member variable in didReceiveRemoteNotification, you  will know if this is from closed or background
    print("Handle push from background or closed\(response.notification.request.content.userInfo)")
}

func showAlertAppDelegate(title: String,message : String,buttonTitle: String,window: UIWindow){
    let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.alert)
    alert.addAction(UIAlertAction(title: buttonTitle, style: UIAlertActionStyle.default, handler: nil))
    window.rootViewController?.present(alert, animated: false, completion: nil)
}
// Firebase ended here

 }

Firebase Cloud Functions

一切都很好但是当X跟随A时,我的设备上没有收到任何通知!

1 个答案:

答案 0 :(得分:0)

我认为您使用了错误的令牌

FMC使用sprecial其令牌

当您在didRegisterForRemoteNotificationsWithDeviceToken收到ios令牌时,您将收到带

的FCM令牌

let fcmToken = Messaging.messaging().fcmToken

let apnsToken = Messaging.messaging().apnsToken

使用fcmToken和FCM会向您的设备发送通知

希望这个帮助