LoginSignup
8
6

More than 5 years have passed since last update.

【iOS】Firebase Cloud Messaging を使って Silent Notification 受信する

Posted at

Firebase Cloud Messaging を使って、iOS の Silent Notification(サイレント通知)を実装してみました。

今回は、Firebase の機能のひとつである、Firebase Cloud Messagingを使って実装してみました。

Firebase Cloud Messaging の設定

基本的には、Firebaseの公式ドキュメントの通りやるのが、なんだかんだで一番てっとり早いです。
iOS に Firebase Cloud Messaging クライアント アプリを設定する

こちらの記事も参考になります。
【iOS10】Firebaseでサイレント通知を行う

プロジェクトの設定

上記のFirebase公式ドキュメントに付随して、さらに設定を行います。

まず、Topicへ登録を行います。
Topic機能を使うことで、通知を受ける端末をグループ管理することができます。
今回は全て同じトピックに登録するので、決め打ちとします。

以下の内容を、AppDelegateに追加します。

func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
    Messaging.messaging().subscribe(toTopic: "ios")
}

続いて、アプリプロジェクトのCapability設定を行います。
アプリのCapability設定で「Background Modes」をONに。
さらに、「Background fetch」と「Remote notifications」にチェックをいれます。
スクリーンショット 2019-03-21 18.52.21.png

続いて、「Push Notifications」をONにするのも忘れずに。
スクリーンショット 2019-03-21 18.52.28.png

Curl から Silent Notification リクエストを送る

Curl を使ってHTTP POSTをFirebaseに送信することで、指定したTopicにSilent Notificationを送ることができます。

$ curl --header "Authorization: key=API_KEY" --header Content-Type:"application/json" https://fcm.googleapis.com/fcm/send -d "{\"to\": \"/topics/ios\",\"content_available\":true}"

API_KEY の部分は、Firebaseの設定画面からAPI KEYを調べてそれを入れてやります。
Firebaseのコンソール画面の「設定」→「クラウドメッセージング」から「サーバーキー」とあるものが、API_KEYとなります。
スクリーンショット 2019-03-21 19.02.56.png

これでうまく Silent Notification が送信できていれば、アプリがバックグラウンドにいたとしても、AppDelegateにある以下の関数が呼ばれます。

func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
    print(#function)
}

Silent Notification ですので、当然通知バーにはなんの通知もきません。

8
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
6