LoginSignup
14
7

More than 3 years have passed since last update.

Firebase Admin SDKを使ったサイレントPush通知

Last updated at Posted at 2019-07-12

はじめに

iosでは、画面にPUSH通知表示させず、PUSH通知を受信した時に30秒間だけ処理を実行できるサイレント通知(バックグランド通知)があります。ここでは、Firebase Admin SDKを使ってサイレント通知の送信方法を書きます。

サイレント通知とは

iosでは、バックグランド通知(サイレント通知と呼ばれることもある)を利用することで、30秒間だけアプリの処理を実行することができます。
具体的には、以下の`content-available'を指定しているPUSH通知を受信した時に、アプリが起動されます。PUSH通知を受信した時に、アプリは、AppDelegate.swiftのメソッドであるapplication(_:didReceiveRemoteNotification:fetchCompletionHandler:)が呼ばれます。

{
   "aps" : {
      "content-available" : 1
   },
}

サイレント通知送信の実装

以下のコードは、サイレント通知の送信コードです。content_available = Trueの部分が、サイレント通知に必要な部分です。他の部分は、Firebase Admin SDKを使ったPUSH通知の基本的な方法は、別の記事で書いていますのでそちらを参照ください。

  • YOUR_REGISTRATION_TOKENでしていしたスマホへPush通知を送信します。
  • path/to/serviceAccountKey.jsonは、ダウンロードした秘密鍵のファイルを指定します。
import firebase_admin
from firebase_admin import credentials
from firebase_admin import messaging

cred = credentials.Certificate("path/to/serviceAccountKey.json")
firebase_admin.initialize_app(cred)

# This registration token comes from the client FCM SDKs.
registration_token = 'YOUR_REGISTRATION_TOKEN'

# See documentation on defining a message payload.
notification = messaging.Notification(
    title = 'test server',
    body = 'test server message',
)
token = registration_token

apns = messaging.APNSConfig(
   payload = messaging.APNSPayload(
       aps = messaging.Aps( content_available = True ) # ここがバックグランド通知に必要な部分
   )
)

message = messaging.Message(
    notification=notification,
    apns=apns,
    token=token,
)

# Send a message to the device corresponding to the provided
# registration token.
response = messaging.send(message)
# Response is a message ID string.
print('Successfully sent message:', response)

参考文献

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