非Ejected CRNA应用能否通过AWS Amplify配置推送通知?
适配非Ejected CRNA应用的AWS Amplify推送通知配置方案
确实,AWS Amplify官方文档里的推送通知集成方案对非ejected的CRNA(Create React Native App)应用不太友好——毕竟官方方案默认是针对已经 eject、能直接修改原生代码的项目设计的。不过别担心,我们有适配这类应用的可行方案,主要是通过Amplify JavaScript库搭配社区推送通知工具来实现,具体步骤如下:
1. 安装必要依赖
首先确保你的项目里已经装好AWS Amplify核心库,同时需要安装适配CRNA环境的推送通知工具包。这里推荐用react-native-push-notification,CRNA环境下不需要手动link,因为Expo已经内置了相关原生桥接支持:
npm install aws-amplify react-native-push-notification @react-native-community/push-notification-ios # 或者用yarn yarn add aws-amplify react-native-push-notification @react-native-community/push-notification-ios
2. 配置AWS Amplify后端推送资源
你可以通过Amplify CLI快速配置后端的推送通知服务(Pinpoint):
- 运行
amplify add notifications,按照终端提示选择对应的平台(APNs用于iOS,FCM用于Android),上传对应的证书或密钥 - 配置完成后执行
amplify push,等待云端资源部署完成
3. 前端集成与设备令牌注册
在你的CRNA应用入口文件(比如App.js)里,完成以下两步核心配置:
3.1 初始化AWS Amplify
先导入并初始化Amplify,关联你刚才部署的云端资源:
import Amplify from 'aws-amplify'; import awsconfig from './aws-exports'; Amplify.configure(awsconfig);
3.2 配置推送通知监听与令牌注册
用react-native-push-notification获取设备的推送令牌,再把这个令牌注册到AWS Pinpoint服务,这样Pinpoint就能给这个设备推送消息了:
import PushNotification from 'react-native-push-notification'; import { Notifications } from 'aws-amplify'; // 初始化推送通知配置 PushNotification.configure({ // Android端的令牌回调 onRegister: (token) => { // 将Android设备令牌注册到Pinpoint,平台标识用'GCM' Notifications.Push.registerDevice(token.token, { platform: 'GCM' }); }, // iOS端的令牌回调(注意:如果是Expo环境,可能需要单独处理权限请求) onRegister: (token) => { // iOS平台标识用'APNS', sandbox环境用'APNS_SANDBOX' Notifications.Push.registerDevice(token.token, { platform: 'APNS' }); }, // 处理收到的推送通知 onNotification: (notification) => { console.log('收到推送:', notification); // 这里可以加自定义逻辑,比如弹出提示、跳转页面等 }, // iOS权限配置 permissions: { alert: true, badge: true, sound: true }, popInitialNotification: true, requestPermissions: true });
4. 关键注意事项
- 版本兼容性:因为CRNA/Expo环境不能修改原生代码,一定要确保
react-native-push-notification的版本和你当前使用的Expo版本兼容,建议选最新的稳定版 - 平台标识正确性:Android必须用
GCM,iOS根据环境选APNS(生产)或APNS_SANDBOX(测试),否则令牌注册会失败 - 测试验证:可以登录AWS Pinpoint控制台,找到对应的项目,发送测试推送来验证设备是否能正常接收
如果你用的是Expo Managed Workflow(CRNA的演进版),也可以替换成Expo官方的expo-notifications库来获取令牌,再注册到Pinpoint,兼容性会更好,步骤和上面类似,只是获取令牌的API换成Expo的即可。
内容的提问来源于stack exchange,提问作者Ankit Kante
相关产品推荐
相关产品推荐

