Show image in UNNotificationServiceExtension 圖片推播實作方法 2 - Python apns2發送推播

--

(apns2, Python, UNNotificationServiceExtension)

如果不透過Firebase的Cloud Messaging發送推播訊息
可以參考本文使用Python的apns2套件發送

取得 auth_key_path

可參考下方網誌取得P8憑證

auth_key_path是存放p8的資料夾路徑

取得 auth_key_id

在Apple developer 的Certificates, Identifiers & Profiles中

Keys分頁裡點開設定的p8 key

點進去Detail畫面中,取得Key ID資訊

auth_key_id是Key ID

取得team_id

登入Apple的develpoer網頁

右上角可以切換team

下方的Membership details中,取得Team ID資訊

team_id是Team ID

Python安裝apns2套件

透過終端機安裝apns2套件

pip3 install apns2

推播訊息內容:

# 創建 Payload
alert = PayloadAlert(title = "推播", body = 'Go!', launch_image = 'https://img.rttt.net/2021/08/31/114cd755ecacb.gif')

payload = Payload(alert=alert, sound="default",
badge=1, mutable_content=True)

app收到的格式如下

圖片可以寫在PayloadAlert,也可以透過Payload的custom定義

# 創建 Payload
alert = PayloadAlert(title = "推播", body = 'Go!')

payload = Payload(alert=alert, sound="default",
badge=1, mutable_content=True)

launch_image="https://img.rttt.net/2021/08/31/114cd755ecacb.gif"
custom_data = {'image_url': launch_image}
payload.custom = custom_data

收到的內容格式如下

再依序寫入 topic, auth_key_path, auth_key_id, team_id 資訊

# 設定推送目標設備的 bundle ID
topic = ''

# 設定 token based 認證的憑證信息
auth_key_path = '/Users/xxx.p8'
auth_key_id = ''
team_id = ''

完整範例

###############################################################################
import collections
from apns2.client import APNsClient
from apns2.payload import Payload, PayloadAlert
from apns2.credentials import TokenCredentials

# 設定推送目標設備的設備 device token
token_hex = ''

# 創建 Payload
alert = PayloadAlert(title = "推播", body = 'Go!', launch_image = 'https://img.rttt.net/2021/08/31/114cd755ecacb.gif')
payload = Payload(alert=alert, sound="default",
badge=1, mutable_content=True)

'''
# 另一個方式推播帶圖
alert = PayloadAlert(title = "推播", body = 'Go!')

payload = Payload(alert=alert, sound="default",
badge=1, mutable_content=True)

launch_image="https://img.rttt.net/2021/08/31/114cd755ecacb.gif"
custom_data = {'image_url': launch_image}
payload.custom = custom_data
'''

# 設定推送目標設備的 bundle ID
topic = ''

# 設定 token based 認證的憑證信息
auth_key_path = '/Users/xxx.p8'
auth_key_id = ''
team_id = ''
token_credentials = TokenCredentials(auth_key_path = auth_key_path,
auth_key_id = auth_key_id,
team_id = team_id)

# 創建 APNs 客户端
client = APNsClient(credentials = token_credentials,
use_sandbox = True)

# 将推送通知添加到批量列表中
Notification = collections.namedtuple('Notification', ['token', 'payload'])
notifications = [Notification(payload = payload,
token = token_hex)]

# 发送批量推送通知
client.send_notification_batch(notifications = notifications,
topic = topic)

實際測試

Visual Studio Code執行

--

--