我有一个 iOS 应用程序,其后端由MobileHub
、和. 我注意到 的功能已被 取代,我想使用这项新服务创建一个通知系统。API Gateway
Lambda
DynamoDB
SNS
MobileHub
Pinpoint
当用户通过 . 创建新帖子时API Gateway
,将触发 lambda 函数,我想我可以通过Pinpoint
. 但我在 .com 的官方网站上找不到任何示例或参考文档Pinpoint
。
你有这个场景的任何资源或任何想法吗?非常感谢!
我有一个 iOS 应用程序,其后端由MobileHub
、和. 我注意到 的功能已被 取代,我想使用这项新服务创建一个通知系统。API Gateway
Lambda
DynamoDB
SNS
MobileHub
Pinpoint
当用户通过 . 创建新帖子时API Gateway
,将触发 lambda 函数,我想我可以通过Pinpoint
. 但我在 .com 的官方网站上找不到任何示例或参考文档Pinpoint
。
你有这个场景的任何资源或任何想法吗?非常感谢!
取决于您所说的通知的含义,我假设您想向特定用户(Pinpoint 端点)发送推送通知。
Pinpoint 将与用户关联的每个设备存储为“端点”,通常由 AWS 客户端分析库(例如放大分析)创建。
使用放大分析库,我调用updateEndpoint
,以便我可以指定userId
Lambda 可用的,以及设备令牌并删除optOut
,以便用户可以接收推送通知:
Address
- 用户接受推送通知权限生成的令牌(iOS)optOut
-NONE
这样他们就可以接收推送通知userId
- 用户的唯一 ID(Cognito 的子)userId
现在您可以使用Pinpoint SDK发送推送通知。
const sendMessagesParams = {
ApplicationId: process.env.PINPOINT_APP_ID,
SendUsersMessageRequest: {
Users: {
[receiverUserId]: {}
},
MessageConfiguration: {
APNSMessage: {
Action: 'OPEN_APP',
Title: 'Message received',
SilentPush: false,
Body: `You have a new message`
},
GCMMessage: {
Action: 'OPEN_APP',
Title: 'Message received',
SilentPush: false,
Body: `You have a new message`
}
}
}
};
console.log('sendMessagesParams', JSON.stringify(sendMessagesParams));
pinpoint.sendUsersMessages(sendMessagesParams, (sendMessagesErr, sendMessagesData) => console.log('push sent')
对于您的特定场景,我设置了一个DynamoDB 流并在表中的记录发生更改时触发 Lambda 。创建 lambda 后,您可能需要手动添加 IAM 权限。
来源
我一直在努力让 lambda 函数正常工作,所以请将此答案视为对 Dylan w 答案的补充。
import PushNotification from '@aws-amplify/pushnotification';
import Analytics from '@aws-amplify/analytics';
PushNotification.onRegister((token) => {
Analytics.updateEndpoint({
address: token,
channelType: 'APNS',
optOut: 'NONE',
// Customized userId
userId: "e236e3ea-bas9-4eae-967e-0eb9bcaca26d" // Example
})
});
'use strict';
const AWS = require('aws-sdk');
exports.handler = async (event, context) => {
var pinpoint = new AWS.Pinpoint();
const sendMessagesParams = {
ApplicationId: <YOUR_APPLICATION_ID>, // Find it in Pinpoint->All projects
SendUsersMessageRequest: {
Users:{<USER_ID>:{}}, // The same userId as set on the client. This way you can "follow" people if they switch device
MessageConfiguration:{
APNSMessage:{
Action:"OPEN_APP",
Title:"Message received",
Body:"You have a new message"
}
}
}
};
return await new Promise( (resolve, reject) => {
pinpoint.sendUsersMessages(sendMessagesParams, (sendMessagesErr, sendMessagesData) => {
if(sendMessagesErr) reject(sendMessagesErr)
if(sendMessagesData) resolve(sendMessagesData)
});
});
};
请注意,对 pinpoint 的调用包含在 promise中。因为pinpoint.sendUserMessages
接受回调,所以继续执行(Node 的异步性质),这将关闭 lambda 函数,并且您将不会从回调函数获得任何输出或收到通知,而无需等待函数完成。
最后,我有一些完美的作品。答案是您必须使用“targetClient”来更新“didRegisterForRemoteNotificationsWithDeviceToken”函数内的端点。
let client = self.pinpoint!.targetingClient
let profile = client.currentEndpointProfile()
print("EndpointId = \(profile.endpointId)")
profile.user?.userId = <YOUR_CUSTOM_ID>
client.update(profile)
这是我的 [AppDelegate.swift] 的样子:(重要部分在“didRegisterForRemoteNotificationsWithDeviceToken”函数内)
import UserNotifications
import AWSPinpoint
class AppDelegate: UIResponder, UIApplicationDelegate {
var pinpoint: AWSPinpoint?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Instantiate Pinpoint
let pinpointConfiguration = AWSPinpointConfiguration.defaultPinpointConfiguration(launchOptions: launchOptions)
// Set debug mode to use APNS sandbox, make sure to toggle for your production app
pinpointConfiguration.debug = true
self.pinpoint = AWSPinpoint(configuration: pinpointConfiguration)
// Present the user with a request to authorize push notifications
self.registerForPushNotifications()
return true
}
func registerForPushNotifications() {
UNUserNotificationCenter.current()
.requestAuthorization(options: [.alert, .sound, .badge]) { [weak self] granted, _ in
print("Permission granted: \(granted)")
guard granted else { return }
// Only get the notification settings if user has granted permissions
self?.getNotificationSettings()
}
}
func getNotificationSettings() {
UNUserNotificationCenter.current().getNotificationSettings { settings in
print("Notification settings: \(settings)")
guard settings.authorizationStatus == .authorized else { return }
DispatchQueue.main.async {
// Register with Apple Push Notification service
UIApplication.shared.registerForRemoteNotifications()
}
}
}
func application(_: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
print("DidRegisterForRemoteNotificationsWithDeviceToken: Start")
let tokenParts = deviceToken.map { data in String(format: "%02.2hhx", data) }
let token = tokenParts.joined()
print("Device Token: \(token)")
// Register the device token with Pinpoint as the endpoint for this user
self.pinpoint!.notificationManager.interceptDidRegisterForRemoteNotifications(withDeviceToken: deviceToken)
//set custom userId and update endpoint
let client = self.pinpoint!.targetingClient
let profile = client.currentEndpointProfile()
print("EndpointId = \(profile.endpointId)")
profile.user?.userId = <YOUR_CUSTOM_ID>
client.update(profile)
}
func application(_: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
print("Failed to register: \(error)")
}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
print("didReceiveRemoteNotification:\(userInfo)")
// Pass this remote notification event to pinpoint SDK to keep track of notifications produced by AWS Pinpoint campaigns.
self.pinpoint!.notificationManager.interceptDidReceiveRemoteNotification(userInfo)
}
}
这是向特定用户发送通知的代码。
'use strict';
const AWS = require('aws-sdk');
const pinpoint = new AWS.Pinpoint({region: 'us-west-2'});
exports.handler = (event, context, callback) => {
const done = (err, data) => {
if(err){
console.log('ERROR:', err);
const response = {
statusCode: 400,
body: JSON.stringify(err)
};
callback(response);
}else{
console.log('SUCCESS:', data);
const response = {
statusCode: 200,
body: JSON.stringify(data)
};
callback(null, response);
}
};
let users = {};
users[<YOUR_CUSTOM_ID>] = {};
const params = {
ApplicationId: PINPOINT_PROJECT_ID,
SendUsersMessageRequest: {
Users: users,
MessageConfiguration: {
APNSMessage: {
Action: 'OPEN_APP',
Title: "Hi, I am AWS Pinpoint.",
SilentPush: false,
Body: "You've got a nice message."
}
}
}
};
pinpoint.sendUsersMessages(params, (err, data)=>{
if(err){
done(err);
}else{
done(null, data);
}
});
};
希望这些对你也有用。
这当然可以使用 Amazon Pinpoint。您可以在此处找到 Javascript SDK 文档。
Pinpoint 有 2 种发送模式。
因此,在您的 Lambda 支持的 API 中,您可以选择直接发送给订阅者(如果您有他们的地址)或可能是整个订阅者段(如果您已将端点加载到 Pinpoint)。