LoginSignup
16
6

More than 5 years have passed since last update.

Go + FCMでiOSアプリにPush通知を送る

Last updated at Posted at 2018-12-18

テレビと深夜ラジオが好きなN高等学校3年生の者です。プログラミングクラスに所属しています。
普段はGAE/Goやってます。
Qiitaを書くのは初めてです。

FCMをご存知でない方はこちら🔽
FCM(Firebase Cloud Messaging)とは

前提条件

個々の端末に送信する

個々の端末にPush通知を送信するには、クライアント側で取得したターゲット端末の登録トークン(RegistrationToken)が必要になります。
今回はクライアント側から登録トークンを受け取った後のサーバー側の処理について記述していきます。

まず、完成のコードはこちら👇(この後、それぞれの解説をします)

import (
    ...
    "firebase.google.com/go"
    "firebase.google.com/go/messaging"
    ...
)

...

ctx := context.Background()
opt := option.WithCredentialsFile(/* Firebaseで生成した秘密鍵のjsonファイル */)

app, err := firebase.NewApp(ctx, nil, opt)
if err != nil {
    return err
}

client, err := app.Messaging(ctx)
if err != nil {
    return err
}

badge := 0
message := &messaging.Message{
    APNS: &messaging.APNSConfig{
        Headers: map[string]string{
            "apns-priority": "10",
        },
        Payload: &messaging.APNSPayload{
            Aps: &messaging.Aps{
                Alert: &messaging.ApsAlert{
                    Title: "留年確定",
                    Body: "レポートの提出期限を超過したため、留年が確定しました",
                },
                Badge: &badge,
            },
        },
    },
    Token: RegistrationToken,
}

response, err := client.Send(ctx, message)
if err != nil {
    return err
}

...

解説

必要なパッケージ

FCMを使用するには
"firebase.google.com/go"
"firebase.google.com/go/messaging"

という2つのパッケージが必要になります。

FCMクライアントの生成

ctx := context.Background()
opt := option.WithCredentialsFile(/* Firebaseで生成した秘密鍵のjsonファイル */)

app, err := firebase.NewApp(ctx, nil, opt)
if err != nil {
    return err
}

client, err := app.Messaging(ctx)
if err != nil {
    return err
}

文言などの各設定

// 通知した際、アプリアイコン右上に表示される数字を設定
// 0の場合は表示されない
badge := 0

message := &messaging.Message{
    APNS: &messaging.APNSConfig{
        Headers: map[string]string{
            // Push通知の優先度を設定
            // デフォルトで10が設定されている
            "apns-priority": "10",
        },
        Payload: &messaging.APNSPayload{
            Aps: &messaging.Aps{
                Alert: &messaging.ApsAlert{
                    // 通知の文言を設定
                    Title: "留年確定",
                    Body: "レポートの提出期限を超過したため、留年が確定しました",
                },
                Badge: &badge,
            },
        },
    },
    // クライアント側で取得したターゲット端末の登録トークンをセットする
    Token: RegistrationToken,
}

Push通知を送信

response, err := client.Send(ctx, message)
if err != nil {
    return err
}

まとめ

FCMを使用することで非常に簡単にGoからiOSアプリにPush通知を送ることが出来ました。
Firebaseの公式のガイドに記載されていますが、Androidの通知やWebPushも今回のように手軽に実装できます。
また、iOS + Android + WebPush の全てに対応させたロジックも組むことが出来ます。

参考資料

メッセージを送信する
Communicating with APNs
Payload Key Reference

16
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
16
6