1
1

More than 3 years have passed since last update.

Fire Storageを監視してサイレントプッシュ通知を送信

Last updated at Posted at 2021-03-13

概要

Fire Storageに画像ファイルのアップロードがなされるとCloud Functionsを通してサイレントプッシュ通知を送信します。

今更感はありますが、ググってもpayloadの記述に統一性がなかったりして割と苦戦しました:sweat:

Stack OverFlowの方でも同じ悩みを抱えていた人がいたので参考になれば幸いです。

なお、本記事ではFirebase CLIや証明書周りについては触れません。
下準備ができている前提で進めます。

環境

  • Xcode 12.4
  • Swift 5
  • nodejs 12

Fire Storage

デフォルトバケットを使用

クライアント

Capability

TARGETS > CapabilitiesよりBackground ModesとPush Notificationsを有効にします。
Background ModesはRemote notificationsにチェックを入れます。
(バックグラウンドで通知を受け取りたい場合はBackground fetchもチェック)

Swift

今回はTopic購読で実装します。

AppDelegate.swift

import Firebase

@main
class AppDelegate: UIResponder, UIApplicationDelegate {

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {

        FirebaseApp.configure()

        // 1. 通知許可
        let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
        UNUserNotificationCenter.current().requestAuthorization(
            options: authOptions,
            completionHandler: { (granted, error) in
                // todo
            })
        application.registerForRemoteNotifications()
        return true
    }

    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        // 2. Topic購読
        Messaging.messaging().subscribe(toTopic: "hoge") { _ in
            // todo
        }
    }

    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any],
                     fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
        // 3. 画像ファイルの名称を取り出す
        guard let imageName = userInfo["imageName"] as? String else {
            return
        }
        print("image name: \(imageName)")
    }
}

Cloud Functions

onFinalize関数でバケットに画像がアップロードされたことを検知します。

index.js
'use strict';

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);

exports.sendSilentNotificationWithTopic = functions.storage.object().onFinalize((object) => {
  const topic = 'hoge';
  const payload = {
    data: {
      imageName: object.name, // 画像名をセット
    },
  };
  const options = {
    contentAvailable: true // サイレントプッシュはtrueにする
  };
  return admin.messaging().sendToTopic(topic, payload, options)
    .then(function(response) {
      return console.log("Successfully sent message:", response);
    })
    .catch(function(error) {
      return console.log("Error sending message:", error);
    });  
});

firebase deployを実行してデプロイします。

実行

  1. Xcodeに実機をつないでRun
  2. Fire Storageに画像ファイルを追加

Xcodeのコンソールログに画像名が表示されれば成功です。
自分はこれで成功したのですが、失敗したらすいません。。。

1
1
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
1
1