how to send/receive mobile notifications with Django and React Native?

Viewed 16

I am implementing notifications for mobile device.

I successfully setup Firebase with my project and can send push notifications to users. But my problem is on iOS when a user denies notification permissions I still need a way to have the notification show up when the user opens the app.

After a little research I found that i could do that with Django Channel Layers, but am still slightly confused on how exactly it works.

From my understanding, on the client side I setup WebSockets, open the WebSocket connection and send the data, which I am able to do.

Then on the server side I setup Django Channels, listen for the open connection and receive the data, which I am also able to do.

My question is how do I send the data to the intended user?

Here's my code:

React Native:

const ws = new WebSocket('ws://ws/notif-socket/');

useEffect(() => {
    ws.onopen = () => {
      console.log('Connected!');
    };
    ws.onerror = e => {
      console.log(e.message);
    };
  }, []);

const data = {
   to_user: user_id.toString(),
   title: 'Notification',
   body: 'User_2 liked your post',
   image: imageURL,
};

ws.send(JSON.stringify(data));

Django:

# models.py
class Notification(models.Model):
    from_user = models.ForeignKey(
        User, on_delete=models.CASCADE, related_name='from_user')
    to_user = models.ForeignKey(
        User, on_delete=models.CASCADE, related_name='to_user')
    title = models.CharField(max_length=100)
    body = models.TextField(default=None, blank=True)
    image = models.CharField(max_length=300, default=None, blank=True)
    date = models.DateTimeField(auto_now_add=True)

# consumers.py
class NotificationConsumer(WebsocketConsumer):

    def connect(self):
        self.accept()

    def receive(self, text_data):
        data = json.loads(text_data)
        print(data)

Should I be using Django Channels for this use case?

Appreciate any help, thanks!!

0 Answers
Related