FCM HTTP v1 API 和通知編輯器支援在顯示通知的負載中發送圖像鏈接,以便在傳送後將圖像下載到設備。此功能支援 Apple 應用程式的圖像和影片(有關檔案大小限制,請參閱 Apple 文件)。
為了能夠在Apple應用程式中接收和處理通知影像,您必須新增通知服務擴充功能。通知服務擴充功能可讓您的應用程式在向最終使用者顯示通知之前處理 FCM 負載中傳遞的映像。
設定通知服務擴展
若要新增服務擴展,請執行所需的設定任務以修改和呈現 APN 中的通知,然後在NotificationService.m
中新增 FCM 擴展幫助程式 API。具體來說,不要使用self.contentHandler(self.bestAttemptContent);
,使用FIRMessaging extensionHelper
完成它,如圖所示:
@interface NotificationService () <NSURLSessionDelegate>
@property(nonatomic) void (^contentHandler)(UNNotificationContent *contentToDeliver);
@property(nonatomic) UNMutableNotificationContent *bestAttemptContent;
@end
@implementation NotificationService
- (void)didReceiveNotificationRequest:(UNNotificationRequest *)request withContentHandler:(void (^)(UNNotificationContent * _Nonnull))contentHandler {
self.contentHandler = contentHandler;
self.bestAttemptContent = [request.content mutableCopy];
// Modify the notification content here as you wish
self.bestAttemptContent.title = [NSString stringWithFormat:@"%@ [modified]",
self.bestAttemptContent.title];
// Call FIRMessaging extension helper API.
[[FIRMessaging extensionHelper] populateNotificationContent:self.bestAttemptContent
withContentHandler:contentHandler];
}
...
建構發送請求
在通知發送請求中,設定以下ApnsConfig選項:
-
fcm_options.image
包含圖像 URL -
headers({ "mutable-content": 1})
以下範例發送請求向所有平台發送通用通知標題,但它還發送圖像。以下是使用者裝置上視覺效果的近似值:
Node.js
const topicName = 'industry-tech';
const message = {
notification: {
title: 'Sparky says hello!'
},
android: {
notification: {
imageUrl: 'https://foo.bar.pizza-monster.png'
}
},
apns: {
payload: {
aps: {
'mutable-content': 1
}
},
fcm_options: {
image: 'https://foo.bar.pizza-monster.png'
}
},
webpush: {
headers: {
image: 'https://foo.bar.pizza-monster.png'
}
},
topic: topicName,
};
getMessaging().send(message)
.then((response) => {
// Response is a message ID string.
console.log('Successfully sent message:', response);
})
.catch((error) => {
console.log('Error sending message:', error);
});
休息
POST https://fcm.googleapis.com/v1/projects/myproject-b5ae1/messages:send HTTP/1.1
Content-Type: application/json
Authorization: Bearer ya29.ElqKBGN2Ri_Uz...HnS_uNreA
{
"message":{
"topic":"industry-tech",
"notification":{
"title":"Sparky says hello!",
},
"android":{
"notification":{
"image":"https://foo.bar/pizza-monster.png"
}
},
"apns":{
"payload":{
"aps":{
"mutable-content":1
}
},
"fcm_options": {
"image":"https://foo.bar/pizza-monster.png"
}
},
"webpush":{
"headers":{
"image":"https://foo.bar/pizza-monster.png"
}
}
}
}
有關訊息正文中平台特定區塊中可用鍵的完整詳細信息,請參閱HTTP v1 參考文件。
透過如圖所示設定mutable-content
,此發送請求使接收用戶端上的服務擴充功能能夠處理有效負載中傳遞的影像。