LoginSignup
3
1

More than 5 years have passed since last update.

[golang]FCMの単一iOS端末にリッチ通知を送る

Last updated at Posted at 2017-05-20

では普通の通知だったので、iOS10からのリッチな通知を送ってみる。

package main

import (
    "bytes"
    "encoding/json"
    "net/http"
)

func main() {
    PostToFCM(
        "##KEY##",
        "hello",
    )
}

type FCMParam struct {
    To           string          `json:"to"`
    Notification FCMNotification `json:"notification"`
    Priority     int             `json:"priority"`
}
type FCMNotification struct {
    Title          string `json:"title"`
    Subtitle       string `json:"subtitle"`
    Body           string `json:"body"`
    Badge          int    `json:"badge"`
    Sound          string `json:"sound"`
    MutableContent bool   `json:"mutable_content"`
    ImageUrl       string `json:"image-url"`
}

func PostToFCM(to string, body string) error {
    n := FCMNotification{
        Title:          "title",
        Subtitle:       "subtitle",
        Body:           body,
        Badge:          0,
        Sound:          "default",
        MutableContent: true,
        ImageUrl:       "https://hogehoge.com/hoge.jpg",
    }
    params := &FCMParam{
        To:           to,
        Notification: n,
        Priority:     10,
    }
    b, err := json.Marshal(params)
    jsonStr := string(b)

    req, err := http.NewRequest(
        "POST",
        "https://fcm.googleapis.com/fcm/send",
        bytes.NewBuffer([]byte(jsonStr)),
    )
    if err != nil {
        return err
    }

    // Content-Type 設定
    req.Header.Set("Content-Type", "application/json")
    req.Header.Set("Authorization", "key=##KEY##")

    client := &http.Client{}
    resp, err := client.Do(req)
    if err != nil {
        return err
    }
    defer resp.Body.Close()

    return err
}

重要なのはここだけで、

        MutableContent: true,
        ImageUrl:       "http://hogehoge.com/hoge.jpg",

mutable_contentをtrueにして適当なキーでurlを送ればいい。

iOSで取得する

↑で飛ばしたimage-urlはiOS側のNotificationServiceの
didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void)

request.content.userInfo["gcm.notification.image-url"]で拾える。プリフィックスが付くので注意。
あとATSの設定がextension毎にあるのでNotificationService側も設定しておかないとhttpの画像送ると出てこない。

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