json - FCM 功能 - 接收通知

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

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

我的index.js部署在firebase上

my index.js codes

我的项目应用程序委托(delegate):

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 时,我的设备上没有收到任何通知!

最佳答案

我认为您使用了错误的 token

FMC 使用其特殊代币

当您在 didRegisterForRemoteNotificationsWithDeviceToken 中收到 ios token 时,您将收到 FCM token

let fcmToken = Messaging.messaging().fcmToken

让 apnsToken = Messaging.messaging().apnsToken

使用 fcmToken,FCM 将向您的设备发送通知

希望这有帮助

关于json - FCM 功能 - 接收通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47684646/

相关文章:

Android 应用在点击通知时启动缓慢

reactjs - 即使在发送消息后,也不会在 React 应用程序中触发 Firebase 云消息传递 onMessage

android - 如何使用 retrofit2 创建 json 对象数组的查询

使用 JAX-RS/RESTEasy 实现 CORS 的 Ajax 请求

swift - 在自定义 cocoapod 框架中使用 Pod 依赖项获取 "use of undeclared type"

objective-c - 谷歌API错误 "Multiple methods named ' initWithArray :' found"

ios - 在两个 View 之间传递数据(在同一个 ViewController 中)

ios - iOS 中什么函数从 Firebase Messaging 接收推送通知?

jquery - 使用 jquery 将数据保存到本地 json 文件

java - 使用 Google HTTP 客户端库从 JSON 结果解析匿名数组