如何在React Native中正确配置Pusher?

问题描述 投票:0回答:1

问题:

在我的网络应用程序中,我已成功连接到频道并发送消息,没有任何问题。这就是我组织我的推送器订阅代码的方式。

window.Pusher = require('pusher-js')

window.Echo = new Echo({
  broadcaster: 'pusher',
  key: my_key,
  cluster: 'ap2',
  forceTLS: true,
  encrypted: true,
  authorizer: (channel, options) => {
    return {
      authorize: (socketId, callback) => {
        httpClient.post('/user/chatauth', {
          "socket_id": socketId,
          "channel_name": channel.name
        })
          .then(response => {
            callback(false, response.data);
          })
          .catch(error => {
            callback(true, error);
          });
      }
    };
  },
})

这里我提供如何添加消息监听部分。

window.Echo.private('chat.' + userSelector.role + userSelector.user_id)
    .listen('.newMessage', ({ chat, user_data }) => {
        console.log(user_data)
        //other logics to update states
    });

之后,我正在使用 React Native 移动应用程序创建相同的逻辑。这就是我在 useEffect 挂钩中以 React Native 组织我的订阅部分的方式。

useEffect(() => {
    if (userSelector) {
        const pusher = new Pusher("my_key", {
            "cluster": "ap2",
            "encrypted": true,
            "channelAuthorization": {
                endpoint: "myURL/api/user/chatauth",
            }
        })
        
        const channel1 = pusher.subscribe('chat.' + userSelector.role + userSelector.user_id)
        
        // You can bind more channels here like this
        // const channel2 = pusher.subscribe('channel_name2')
        channel1.bind('.newMessage', function (data) {
            console.log(data, "data")
        })
        

        return (() => {
            pusher.unsubscribe('chat.' + userSelector.role + userSelector.user_id)
        })
    }

}, [userSelector, isFocused])

我从网站发送消息后,但移动应用程序从未收到该消息。但当我用两个浏览器尝试它时,它的工作方式就像魅力一样。但不能使用移动应用程序。

我做了很多尝试来找出问题所在,但我无法做到。有人可以帮助我完成这项工作吗?谢谢你

react-native pusher
1个回答
-1
投票

兄弟,你有什么想法吗?我和你一样被困住了,我已经阅读了 Pusher 的文档,但没有发现有帮助!!

© www.soinside.com 2019 - 2024. All rights reserved.