Firebase通知 - Firebase云消息传递

时间:2016-07-26 10:20:09

标签: swift firebase firebase-cloud-messaging

在我的应用程序中,我使用Firebase Messaging和我测试来接收通知。 我使用Postman作为休息服务来配置通知的正文如下:

{
"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:.
}


}

有人可以请你解释一下吗?

1 个答案:

答案 0 :(得分:2)

让我们处理didReceiveRemoteNotification中的代码。首先,我们提取应该呈现的视图控制器:

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

 if type == "viewcontroller1" {

 // here we go to start the 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)

注意:收到通知后,您需要检查应用是在后台还是在应用中,或者是在应用之外。对于每个人,您需要对如何以及何时需要显示或呈现视图控制器进行不同的处理。