如何使用FCM(iOS)获取远程通知的内容?

时间:2017-01-14 18:29:54

标签: ios swift firebase push-notification firebase-cloud-messaging

我正在使用FCM向使用此方法的设备发送推送通知

 func push(message: String, toUser: String) {
    var token: String?
    for person in self.users {
        if toUser == person.username && person.firebaseToken != nil {
            token = person.firebaseToken
        }
    }
    if token != nil {
        var request = URLRequest(url: URL(string: "https://fcm.googleapis.com/fcm/send")!)
        request.httpMethod = "POST"
        request.setValue("application/json", forHTTPHeaderField: "Content-Type")
        request.setValue("key=[your FCM Server Key]", forHTTPHeaderField: "Authorization")
        let json = [
            "to" : token!,
            "priority" : "high",
            "notification" : [
                "body" : message
            ]
        ] as [String : Any]
        do {
            let jsonData = try JSONSerialization.data(withJSONObject: json, options: .prettyPrinted)
            request.httpBody = jsonData
            let task = URLSession.shared.dataTask(with: request) { data, response, error in
                guard let data = data, error == nil else {
                    print("Error=\(error)")
                    return
                }

                if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {
                    // check for http errors
                    print("Status Code should be 200, but is \(httpStatus.statusCode)")
                    print("Response = \(response)")
                }

                let responseString = String(data: data, encoding: .utf8)
                print("responseString = \(responseString)")
            }
            task.resume()
        }
        catch {
            print(error)
        }
    }
}

但是这些设备只是在不做任何事情的情况下获取消息。 我也试图保存它的内容。我怎样才能做到这一点?是将其保存到Firebase数据库的唯一选项吗?

感谢。

1 个答案:

答案 0 :(得分:2)

您需要通过AppDelegate处理通知。您将首先在didFinishLaunchingWithOptions中注册通知。因为firebase在第一次启动消息传递时没有密钥,所以您需要注册以观察该值:

    // register for remote notifications:
    if #available(iOS 10.0, *) {
        let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
        UNUserNotificationCenter.current().requestAuthorization(options: authOptions, completionHandler: { (_, _) in })
        UNUserNotificationCenter.current().delegate = self
        FIRMessaging.messaging().remoteMessageDelegate = self
    } else {
        let settings: UIUserNotificationSettings = UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
        application.registerUserNotificationSettings(settings)
    }


    application.registerForRemoteNotifications()

    NotificationCenter.default.addObserver(forName: NSNotification.Name.firInstanceIDTokenRefresh, object: nil, queue: nil, using: tokenRefreshNotification(_:))

然后您需要一种连接到FCM的方法:

extension AppDelegate {
    func connectToFCM() {
        FIRMessaging.messaging().connect { (error) in
            if error != nil {
                print("unable to connect to FCM \(error)")
            } else {
                print("connected to FCM")
            }
        }
    }
}

一种处理新令牌的方法:

extension AppDelegate {
    func tokenRefreshNotification(_ notification: Notification) {
        if let refreshedToken = FIRInstanceID.instanceID().token() {
            UserDefaults.standard.set(refreshedToken, forKey: "registrationToken")
        }

        connectToFCM()
    }
}

最后,您需要实际处理通知。推送通知的实际内容位于'通知'适用于iOS 10及更高版本的对象:

@available(iOS 10, *)
extension AppDelegate : UNUserNotificationCenterDelegate {

    // Receive displayed notifications for iOS 10 devices.
    func userNotificationCenter(_ center: UNUserNotificationCenter,
                            willPresent notification: UNNotification,
                            withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {

        let userInfo = notification.request.content.userInfo

        PushService.handle(userInfo) // do whatever you need with this

    }
}

要处理其他类型的通知,您可以回归旧方式:

func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any]) {
    //user tapped on notification
    PushService.handle(userInfo) // do what you need with the userInfo dict here, which contains the push notification information

}