Я новичок в разработке React Native, я разрабатываю приложение чата с помощью WebSocket.
Я могу отправлять и получать сообщения, но мне нужно показать локальное уведомление, когда сообщение приходит из канала.
Я получаю сообщение и могу показать уведомление при открытии приложения, но если оно работает в фоновом режиме, я не получаю уведомление.
К вашему сведению: я не закрывал приложение, я открыл другое приложение, например WhatsApp или любое другое. Если я получаю сообщение, уведомление также не отображается.
Для локальных push-уведомлений я использую:
https://www.npmjs.com/package/react-native-push-notification
"response-native-push-messages": "3.1.1"
«Reaction-native»: «0,59,8»
Я не хочу использовать какие-либо сторонние службы, такие как FCM
Ниже приведен код для получения и отображения уведомления
import React, {Component} from 'react';
import {Socket} from 'phoenix-socket';
import AsyncStorage from "@react-native-community/async-storage";
import PushNotification from 'react-native-push-notification';
class SocketConnection extends React.Component {
constructor(props) {
console.log('Socket constructor');
super(props);
this.state = {
user_id: '',
company_id: '',
msg: {}
};
PushNotification.configure({
onNotification: function (notification) {
console.log('NOTIFICATION: ', notification);
},
popInitialNotification: true,
requestPermissions: true,
});
}
componentDidMount() {
this.getMessage();
};
getMessage = async () => {
var thatclass = this;
let user = await AsyncStorage.getItem('currentUser');
user = JSON.parse(user);
this.setState({user_id: user.user.id});
this.setState({company_id: user.user.company_id});
console.log('Socket constructor');
this.socket = new Socket('ws://localhost:4000/socket/websocket');
this.socket.connect();
const that = this;
this.socket.onError(function (er) {
console.log('Error');
console.log(er);
that.socket.close();
});
this.socket.onOpen(function (res) {
console.log('Open');
console.log(res)
});
this.channel = this.socket.channel("channel:" + user.user.company_id, {});
this.channel.join()
.receive("ok", resp => {
console.log(resp)
})
.receive("error", resp => {
console.log(resp)
});
if (this.channel) {
this.channel.on('users:' + user.user.id, function (payload) {
console.log(payload);
this.setState = ({
msg: payload,
});
thatclass.sendNotification(payload);
});
}
}
sendNotification(payload) {
console.log(payload);
PushNotification.localNotification({
foreground: true, // BOOLEAN: If the notification was received in foreground or not
userInteraction: false,
ticker: "My Notification Ticker", // (optional)
bigText: payload.message, // (optional) default: "message" prop
color: "red", // (optional) default: system default
priority: "high", // (optional) set notification priority, default: high
visibility: "private", // (optional) set notification visibility, default: private
/* iOS and Android properties */
title: payload.subject, // (optional)
message: "My Notification Message", // (required)
playSound: true, // (optional) default: true
actions: '["archive", "reply"]',
});
};
openIndex(id) {
console.log(id);
}
render() {
return (null);
}
}
export default SocketConnection;