简体   繁体   English

react-native:推送通知+解析

[英]react-native: push notifications + parse

I am currently working on a small app project to learn and try out react-native on iOS. 我目前正在开发一个小型应用程序项目,以便在iOS上学习并尝试使用react-native。 I have some experience with parse (parse.com) and would love to integreate parse in the new app. 我有一些解析(parse.com)的经验,并希望在新的应用程序中集成解析。 Currently, I have no problems including parse js into react-native. 目前,我没有问题,包括解析反应原生的js。 I am able to log in with accounts etc. Now I need to send push notifications to a certain number of users (not all users). 我可以使用帐户等登录。现在我需要向一定数量的用户(并非所有用户)发送推送通知。

What I don't understand is how push notifications should work with react-native and parse. 我不明白的是推送通知应如何与react-native和parse一起使用。 Usually, I would connect a device installation with a user ID and then send a push to a certain number of users (which means to the devices with the corresponding installation). 通常,我会使用用户ID连接设备安装,然后将推送发送给一定数量的用户(这意味着具有相应安装的设备)。 The react-native guide ( https://facebook.github.io/react-native/docs/pushnotificationios.html#content ) doesn't mention anything like that. 本地反应指南( https://facebook.github.io/react-native/docs/pushnotificationios.html#content )没有提到类似的内容。 And even though it gives the parse guide as a reference, I fail to see how I should be able to send pushes via parse. 即使它提供了解析指南作为参考,我也看不出我应该如何通过解析发送推送。 The guide leaves a lot of information to be desired too. 该指南也留下了许多需要的信息。 To what source do these "Listeners" subscribe to? 这些“听众”订阅的来源是什么? From which server am I going to send notifications etc? 我将从哪个服务器发送通知等?

As I understand, parse js is not able to read the current installation. 据我了解,解析js无法读取当前安装。 I hesitate to add Parse iOS to the project too. 我也不愿意将Parse iOS添加到项目中。 This feels unnatural and shouldn't be a required thing to do although it would allow me to read the current installation. 这感觉不自然,不应该是必需的事情,虽然它可以让我阅读当前的安装。 (but still parse js is not able to register that installation in order to subscribe to push notifications). (但仍解析js无法注册该安装以订阅推送通知)。

At this point, I feel a little bit lost. 在这一点上,我感到有点失落。 This piece of information ( https://news.ycombinator.com/item?id=9271687 ) tells me that it should be possible somehow. 这条信息( https://news.ycombinator.com/item?id=9271687 )告诉我它应该可能以某种方式。 I just can't figure out how :( 我只是想不通如何:(

Hope someone can help me with that. 希望有人可以帮助我。 Some advice would be truely appreciated. 一些建议将得到真正的赞赏。

EDIT : react-native implements this behavior by default now. 编辑 :react-native现在默认实现此行为。 The interesting part is the event listener for the register event which now returns the device token. 有趣的部分是register事件的事件监听器,它现在返回设备令牌。 Procedure is pretty straight forward now. 程序现在非常简单。 Just have a look at the docs Also check out the answer by JWindey. 看看文档也看看JWindey的答案。 Has some very important points in them that are needed to actually trigger the events. 其中有一些非常重要的要点是实际触发事件所需要的。

After a while and a lot of trying things out, we came up with an answer today. 经过一段时间和大量的尝试,我们今天想出了答案。 This is our solution and it seems to be working pretty good. 这是我们的解决方案,似乎工作得很好。

We use the following resources: 我们使用以下资源:

Follow the parse guide for push notifications ( https://parse.com/tutorials/ios-push-notifications ) and get everything set up correctly (profiles, certificates etc.). 按照推送通知的解析指南( https://parse.com/tutorials/ios-push-notifications )进行正确设置(配置文件,证书等)。 Using the react-native-remote-push component later on, you don't have to follow the steps 5 and 6. 稍后使用react-native-remote-push组件,您不必执行步骤5和6。

Now add react-native-remote-push to you project. 现在将react-native-remote-push添加到您的项目中。 We had to make some minor adjustments to the code (mainly dealing with legacy objC code), but that may depend on your own project. 我们不得不对代码做一些小的调整(主要是处理遗留的objC代码),但这可能取决于你自己的项目。

Our project has some kind of "starting page" that is shown every time the app is opened. 我们的项目有一些“起始页面”,每次打开应用程序时都会显示。 On this page, we deal with push notification permissions as well as with the registration of the device token and the listener for push notifications. 在此页面上,我们处理推送通知权限以及设备令牌的注册和推送通知的监听器。 Our goal is to mimic the same behavior that we would receive with the parse iOS SDK. 我们的目标是模仿我们使用解析iOS SDK获得的相同行为。

We need to register the device and subscribe to a push channel first. 我们需要先注册设备并订阅推送通道。 react-native-remote-push allows us to handle the permissions and receive a device token. react-native-remote-push允许我们处理权限并接收设备令牌。 We then proceed to use this device token to register this installation via the Rest API. 然后,我们继续使用此设备令牌通过Rest API注册此安装。 This code is part of our componentDidMount() call. 此代码是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 is the required component from react-native-remote-push and registerInstallation is the function containing the Rest API call. 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" and "error" are just some small functions that handle the result of the API call. “processStatus”,“parseJson”和“error”只是一些处理API调用结果的小函数。 I can provide more details if necessary. 如有必要,我可以提供更多细节。 This function allows us to add a lot of information via the "data" object, such as userid, app version, parse version etc., just as you're used to from the iOS SDK. 此功能允许我们通过“数据”对象添加大量信息,例如用户ID,应用程序版本,解析版本等,就像您习惯使用iOS SDK一样。 We only have a basic example working right now, but it should be easy to extend on this basis. 我们现在只有一个基本的示例,但在此基础上应该很容易扩展。 This step was very important for us, because we need to associate every installation with a certain user. 这一步对我们来说非常重要,因为我们需要将每个安装与特定用户相关联。

You should be able to receive push notifications by now. 您现在应该能够接收推送通知。 You can handle them in a "receiveRemoteNotification" function that acts as a listener. 您可以在充当侦听器的“receiveRemoteNotification”函数中处理它们。 A basic function is provided on the website of the react-native-remote-push component. 在react-native-remote-push组件的网站上提供了一个基本功能。

I hope I could share some insight about this topic. 我希望我能分享一些关于这个话题的见解。 If I should go into more detail on certain parts, I'll gladly add some more information. 如果我应该详细介绍某些部分,我很乐意添加更多信息。

I did some investigation with the Parse + react-native combination and have it working. 我使用Parse + react-native组合进行了一些调查并使其正常工作。

You have to add the Parse SDK (follow the guide) to your project, and link all the necessary libraries. 您必须将Parse SDK(按照指南)添加到您的项目中,并链接所有必需的库。

Don't forget to add the steps on point 5: https://parse.com/tutorials/ios-push-notifications . 不要忘记在第5点添加步骤: https//parse.com/tutorials/ios-push-notifications

Then add RCTPushNotificationManager.h + m (from react-native/Libraries) to your project. 然后将RCTPushNotificationManager.h + m(来自react-native / Libraries)添加到您的项目中。 After that, add the following in AppDelegate.m: 之后,在AppDelegate.m中添加以下内容:

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
[[NSNotificationCenter defaultCenter] postNotificationName:@"RemoteNotificationReceived"
                                                    object:self
                                                  userInfo:userInfo];
}

That should do it. 应该这样做。

The official PushNotificationIOS has register event, which we can obtain token from. 官方PushNotificationIOS有register事件,我们可以从中获取令牌。 So, with having @MrMuetze's REST API, I could install the device to Parse. 因此,有了@MrMetet的REST API,我可以将设备安装到Parse。

PushNotificationIOS.addEventListener('register', function(token){
 registerInstallation({
   "deviceType": "ios",
   "deviceToken": token,
   "channels": ["global"]
 })
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM