EDIT:react-native 现在默认实现此行为。有趣的部分是注册事件的事件监听器,它现在返回设备令牌。现在程序非常简单。只需看一下docs https://facebook.github.io/react-native/docs/pushnotificationios.html#content另请查看 JWindey 的答案。其中有一些非常重要的点,需要实际触发事件。
经过一段时间的尝试和大量的尝试,我们今天找到了答案。这是我们的解决方案,看起来效果很好。
我们使用以下资源:
- 反应本机
- parse-js
- 解析 REST API
- 反应本机远程推送(https://github.com/darylrowland/react-native-remote-push https://github.com/darylrowland/react-native-remote-push)
请遵循推送通知的解析指南(https://parse.com/tutorials/ios-push-notifications https://parse.com/tutorials/ios-push-notifications)并正确设置所有内容(配置文件、证书等)。稍后使用react-native-remote-push组件,您不必遵循步骤5和6。
现在将react-native-remote-push 添加到您的项目中。我们必须对代码进行一些小的调整(主要处理遗留的 objC 代码),但这可能取决于您自己的项目。
我们的项目有某种“起始页面”,每次打开应用程序时都会显示该页面。在此页面上,我们处理推送通知权限以及设备令牌和推送通知侦听器的注册。我们的目标是模仿使用解析 iOS SDK 收到的相同行为。
我们需要先注册设备并订阅推送通道。 react-native-remote-push 允许我们处理权限并接收设备令牌。然后,我们继续使用此设备令牌通过 Rest API 注册此安装。这段代码是我们的 componentDidMount() 调用的一部分。
var PushManager = require('./RemotePushIOS');
var registerInstallation = require('./Installation');
componentDidMount() {
PushManager.requestPermissions(function(err, data) {
if (err) {
console.log("Could not register for push");
} else {
registerInstallation({
"deviceType": "ios",
"deviceToken": data.token,
"channels": ["global"]
});
}
});
PushManager.setListenerForNotifications(this.receiveRemoteNotification);
}
PushManager 是react-native-remote-push 所需的组件,registerInstallation 是包含Rest API 调用的函数。
/**
* registers an installation
* data should look like the following:
* {
* "deviceType": "ios", // or "android"
* // if android is targeted set
* // "pushType": "gcm",
* // "GCMSenderId": "56712320625545", // whatever the later means
* "deviceToken": "29e32a686fd09d053e1616cb48",
* "channels": [
* ""
* ]
* };
* for more information visit:
* https://www.parse.com/docs/rest#installations-uploading
*/
var registerInstallation = function(data) {
var url = "https://api.parse.com";
url += "/1/installations";
fetch(url, {
method: 'post',
headers: {
'Accept': 'application/json',
'X-Parse-Application-Id': PARSE_APP_ID,
'X-Parse-REST-API-Key': PARSE_REST_KEY,
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
})
.then(processStatus)
.then(parseJson)
.catch(error);
};
module.exports = registerInstallation;
“processStatus”、“parseJson”和“error”只是一些处理 API 调用结果的小函数。如有必要,我可以提供更多详细信息。此函数允许我们通过“数据”对象添加大量信息,例如用户 ID、应用程序版本、解析版本等,就像您习惯从 iOS SDK 中一样。我们现在只有一个基本的示例,但在此基础上应该很容易扩展。这一步对我们来说非常重要,因为我们需要将每个安装与特定用户相关联。
您现在应该能够接收推送通知。您可以在充当侦听器的“receiveRemoteNotification”函数中处理它们。在react-native-remote-push组件的网站上提供了一个基本的功能。
我希望我能分享一些关于这个话题的见解。如果我应该更详细地了解某些部分,我很乐意添加更多信息。