Quantcast
Channel: Node.jsタグが付けられた新着記事 - Qiita
Viewing all articles
Browse latest Browse all 8916

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

$
0
0

概要

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
importFirebase@mainclassAppDelegate:UIResponder,UIApplicationDelegate{funcapplication(_application:UIApplication,didFinishLaunchingWithOptionslaunchOptions:[UIApplication.LaunchOptionsKey:Any]?)->Bool{FirebaseApp.configure()// 1. 通知許可letauthOptions:UNAuthorizationOptions=[.alert,.badge,.sound]UNUserNotificationCenter.current().requestAuthorization(options:authOptions,completionHandler:{(granted,error)in// todo})application.registerForRemoteNotifications()returntrue}funcapplication(_application:UIApplication,didRegisterForRemoteNotificationsWithDeviceTokendeviceToken:Data){// 2. Topic購読Messaging.messaging().subscribe(toTopic:"hoge"){_in// todo}}funcapplication(_application:UIApplication,didReceiveRemoteNotificationuserInfo:[AnyHashable:Any],fetchCompletionHandlercompletionHandler:@escaping(UIBackgroundFetchResult)->Void){// 3. 画像ファイルの名称を取り出すguardletimageName=userInfo["imageName"]as?Stringelse{return}print("image name: \(imageName)")}}

Cloud Functions

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

index.js
'use strict';constfunctions=require('firebase-functions');constadmin=require('firebase-admin');admin.initializeApp(functions.config().firebase);exports.sendSilentNotificationWithTopic=functions.storage.object().onFinalize((object)=>{consttopic='hoge';constpayload={data:{imageName:object.name,// 画像名をセット},};constoptions={contentAvailable:true// サイレントプッシュはtrueにする};returnadmin.messaging().sendToTopic(topic,payload,options).then(function(response){returnconsole.log("Successfully sent message:",response);}).catch(function(error){returnconsole.log("Error sending message:",error);});});

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

実行

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

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


Viewing all articles
Browse latest Browse all 8916

Trending Articles