swift - Firebase 通知 - Firebase 云消息传递

标签 swift firebase firebase-cloud-messaging

在我的应用程序中,我正在使用 Firebase Messaging,并且正在测试接收通知。 我正在使用 Postman作为 Rest 服务来配置通知的主体,如:

{
"to": "/topics/test",
"priority": "high",
"notification": {
    "title": "Test",
    "body": "New",
    "badge": "0"
},
"data": {
    "foo": "bar"
}
}

证书没问题。我不明白如何以编程方式启动 ViewController 查看传递的数据。例如,如果数据包含:

"data": {
  "foo": "viewcontroller1"
}

我想在用户点击通知时启动 ViewController1。

我只能在AppDelegate中打印数据?如何使用传递的值?

这是我的 AppDelegate.swift:

import UIKit
import Firebase
import FirebaseMessaging

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

var window: UIWindow?

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

    let notificationTypes : UIUserNotificationType = [UIUserNotificationType.Alert, UIUserNotificationType.Badge, UIUserNotificationType.Sound]
    let notificationSettings = UIUserNotificationSettings(forTypes: notificationTypes, categories: nil)
    application.registerForRemoteNotifications()
        application.registerUserNotificationSettings(notificationSettings)

    return true
}

// [START refresh_token]
func tokenRefreshNotification(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.
    connectToFcm()
}

// [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.")
        }
    }
}

//Receive and handle messages
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject], fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) {
    // Print message ID.
    print("Value for foo -> \(userInfo["foo"])")


    //start viewcontroller programmatically



}

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.
    // 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 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) {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}


}

有人可以解释一下吗?

最佳答案

让我们处理 didReceiveRemoteNotification 中的代码,首先我们提取应该呈现哪个 View Controller :

let type = userInfo["foo"] as! String

 if type == "viewcontroller1" {

 // here we go to start the view controller


 }

您将需要使用帮助方法找到最顶层的 View Controller 以呈现在它之上。

func getTopViewController()->UIViewController{

    if var topController = UIApplication.sharedApplication().keyWindow?.rootViewController {
        while let presentedViewController = topController.presentedViewController {
            topController = presentedViewController
        }
        return topController
        // topController should now be your topmost view controller
    }
    return UIViewController()
}

要启动一个 ViewController,您应该在 Storyboard 中为它创建一个标识符。让我们说它也被称为:viewcontroller1然后:

    let storyboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateViewControllerWithIdentifier("viewcontroller1") as! viewcontroller1
self.getTopViewController().presentViewController(vc, animated: true, completion: nil)

注意:收到通知时,您需要检查应用是在后台还是在应用内还是在应用外。对于每一个都有不同的处理方式和时间,您需要显示或展示您的 View Controller 。

关于swift - Firebase 通知 - Firebase 云消息传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38587177/

相关文章:

swift - 如何在嵌套的 Firebase 异步 observeSingleEvent() 方法 Swift 中使用 DispatchGroup?

java - 如何获取子级内部的 dataSnapshot.getChildrenCount()

android - FCM 需要多长时间才能将推送通知发送到一个大基数的主题

ios - 快速检查 JSON 响应 nil

swift - case 在 if-case 中是如何工作的

ios - 如何识别左/右滑动手势?比 UISwipeGestureRecognizer.direction.right/left 更宽松

php - 使用 PHP 执行 cURL 发送推送通知

ios - UISearchController黑屏

ios - Firebase 和 Swift : Update user information in realtime on app after it updates on firebase

android - 如何使 GCM/FCM 通知类型消息不可折叠