Search code examples
androidiosreact-nativewebsocketreact-native-push-notification

React Native handle socket connection's events when app is in background?


I'm working on Chat app using React native and WebSocket everything works fine in active mode but when you push the home button to make the app in background mode, the WebSocket onMessage events function is not triggered

The good thing is that WebSocket connection is still connected but the events function not triggered.

I just want to push the notification when receiving a message in the background mode.

I did a research and I found that I need to run a silent background audio track at all times(some said this illegal way).

Is there a legal API to keep a connection alive in the background?

Do I need to re-connect the socket connection in the background mode

My code

events = (data) =>{

    if(data[0].message){
          if(this.state.appState !== 'active'){
             console.log('check here') // not working when the app in background mode
              PushNotification.localNotification({// not working when the app in background mode
                    message: data[0].message, 
                    number: 1,
                    title: 'a new message from: '+data[0].username,

                });
            }else{
                this.setState({messages: data[0]})
            }
    }
}


socketConnect = () =>{
        AsyncStorage.getItem('token').then((token) => {
        let connection = new wamp.Connection({ url: 'wss://*******/',
            realm: 'realm',
            authmethods: ['jwt'],
        });
        connection.onopen = (session, detalis) => {

            session.subscribe('messages', this.events);
        };
        connection.open();

        })
    };

Solution

  • I did a research and I found that I need to run a silent background audio track at all times(some said this illegal way).

    Yes, that would definitely result in a rejection by the Apple/Google app review team.

    Is there a legal API to keep a connection alive in the background?

    Actually you don't need that (see solution below)

    Solution:

    I assume you have a server, where you manage all the websocket connections and route the message to the expected client. You can use firebase cloud messaging to send the user an ios/android push notification, which informs him/her that there is a new message. Of course you need FCM on both your server and app side. For the app part you could use for example react-native-firebase. For the server there are several libraries available. Now there are two cases:

    case 1)

    If the app is already in the foreground, you can either show a LocalNotification via FCM(react-native-firebase) or you just use your websocket connection to display the message.

    case 2)

    Your app is in background, again you send a push notification via FCM from your server. The big advantage is that FCM communicates with the Apple Push Notification Service and the Google Cloud Messaging Service (btw google will soon just use FCM). That means your user gets a native push notification with a preview text or a full message (that's up to you). Then the user clicks on the notification and your app opens again. At this point you can reconnect to your websocket and then you can continue with your normal app behavior.

    Additional remarks:

    1. This is probably the only legal way
    2. It's much more energy efficient to use APNS/GMS/FCM than keeping the app always in background