Internship experiences can vary substantially from company to company. At PubNub however, interning means learning new languages and skills that will boost your career. The chance to learn from everyone, including Chief Officers, is invaluable. Every time we had a question when working with a new language or framework, there was someone who could explain these concepts in depth.
As a squad of four Developer Relations interns, designing a project that synchronizes with our use of social media was important. Out of a brainstorming session, with many great ideas, came PubMoji: an app that billows floating emojis over your avatar to communicate your mood in real time with people around the world! Find out how people are feeling and learn what’s happening anywhere at any time. PubMoji allows you to gauge reactions to events on a global scale.
We decided to open-source PubMoji so others can use our code as a reference to build their own app.
For an amazing overview and more information on the app, visit the PubMoji product page.
Mobile Apps for Android and iOS with React Native
PubMoji is built using React Native and PubNub’s React SDK. This made it easy to implement real-time chat and live geolocation updates. We chose React Native to shorten our deployment time by developing, maintaining and publishing a single codebase. Instead of setting up a server, and creating connections to that server, we used multiple PubNub features with simple API calls. This gave us more time to focus on the app itself and to provide users with a connected shared experience.
Let’s go into detail on how we implemented features, such as chat messaging, message filtering, geolocation tracking, and online user counts in our app.
React Native Real-time Chat Messaging
While creating PubMoji, we wanted the focus to be on bringing everyone together. Although our emojis can give our emotional sentiment out to the world, it does not allow us to share exactly what we want to say.
Implementing a RuneScape style chat system was the solution. Whenever someone wants to send a message, they tap on the message box. The keyboard pops up, pushes the screen up, and the user can type their chat message. The messages appear in real time centered over the user’s avatar and disappear in 5 seconds from everyone’s screen. Look at the code below to learn how to have an input component publish a message when a user presses enter.
publishMessage = () => { this.pubnub.publish({ message: { uuid: this.pubnub.getUUID(), message: this.state.message, }, channel: 'global' }); } render() { return ( <Input placeholder="Type a message..." onSubmitEditing={this.publishMessage} value={this.state.message} onChangeText={(text) => this.setState({ message: text })} /> ); }
This code utilizes PubNub Pub/Sub, a quick and easy way to get your payloads (strings, numbers, objects) across the world in an instant. These payloads can be up to 32KB in size. For reference, here’s some guidance on how many text characters fit in a 32KB message!
Message Filtering
We wanted to create a safe environment where people can freely communicate how they are feeling. We didn’t want to restrict what people say, but we took some precautions so people wouldn’t write offensive things.
To accomplish this, we used a chat message profanity filter from PubNub’s BLOCKS Catalog, a large collection of predefined and customizable Functions. By doing so, it was easy to set up and deploy the pre-built module for our app which would catch and filter out any swear words, while replacing them with special characters (****) before the messages arrived to the clients.
What are Functions?
A Function is a process that runs in a serverless environment to simplify deploying custom, real-time logic and allows for transforming, enriching, and filtering messages as they route through PubNub’s Data Stream Network. The functions are JavaScript handlers that are executed in response to publishing a message on a channel or in response to an HTTP request. Some use cases for Functions include:
- Translating multi-language chat conversations in-network, with low latency
- Utilizing IoT sensors and serving an event when something occurs, such as a temperature anomaly
- Filtering messages based on their attributes so that only messages with the right values are passed to the subscribed clients
- Triggering an alert when a secure message meets certain criteria, such as email, text message, mobile push notification, etc.
React Native Real-time Map Geolocation Tracking
The main feature of PubMoji is to communicate how you are feeling to others. This wouldn’t be possible without real-time geolocation updates, which are featured on PubMoji’s map. It shows where users are located and tracks user movement as long as the app is open.
What if users don’t want to share their location? We made it possible to control this with a toggle button. Users can toggle their location submission on or off anytime they want! This way, a user can control when they want to inform the app of their GPS location.
To integrate MapView into React Native, we used Airbnb’s react-native-maps. While geolocation worked well in iOS, we encountered some issues in Android. Occasionally, the user’s avatar wouldn’t show up on the map because the location request timed out. To fix this problem, we implemented react-native-geolocation-service, an open-source library that solves location timeout issues for Android devices, and still works with those on iOS.
// Check if user has granted permission to get their location const granted = await this.hasLocationPermission(); if (granted) { Geolocation.getCurrentPosition( position => { // Get the user's coordinates and call this method to publish to the global channel addUserLocation(position); }, error => console.log("Maps Error: ", error), { enableHighAccuracy: false, distanceFilter: 100 } ); }
The location coordinates and permission are stored in the React State.
constructor(props) { super(props); //... PubNub Object //Base State this.state = { currentLoc: { //Track user's current location latitude: -1, longitude: -1 }, userCount: 0, //track number of users on the app users: new Map(), //store data of each user in a Map allowGPS: true, //toggle the app's ability to gather GPS data of the user //Remaining state variables }; //Initialize PubNub }
React Native Online User Count
One cool feature in PubMoji is the user count badge that displays the number of users currently connected to the app.
Anytime a user joins or exits the app, the method updateUserCount() is called.
updateUserCount = () => { this.pubnub.hereNow({ includeUUIDs: true, includeState: true }, function (status, response) { // handle status, response this.setState({userCount: response.totalOccupancy}); }); };
This method retrieves the total occupancy count of the channel by implementing the hereNow() function, which is a call used in Presence. By using Presence, we can easily retrieve the number of users in the app.
What is Presence?
Presence enables real-time detection and streaming of updates as device and user state changes. Some use cases for Presence include:
- Online/Offline status for when a device connects/disconnects
- IoT sensors that stream real-time updates as device state is updated, such as humidity changes
- A collaborative environment that shows what users are doing, like who is currently viewing a collaborative document
- Multiplayer games that display the number of people waiting in the lobby
The PubMoji Dev Team
Building PubMoji was a group effort where everyone brought their own expertise and knowledge. PubMoji would not have been possible without the hard work of the PubNub summer 2019 Developer Relations Interns:
- Cameron Akhavan (@Cameron_Akhavan, Github)
- Lovdeep Singh (@Lovdeep7, Github)
- Oscar Castro (@realoscarcastro, Github)
- Samba Diallo (@sambajahlo, Github)
Special thanks to our manager, Adam Bavosa (@realadambavosa), for guiding and helping us throughout our internship.
If you want to build a React Native app similar to PubMoji, be sure to check out our React Native tutorials that range from building a Real-time Multiplayer Tic Tac Toe Game to setting up Instant Mobile Push Notifications.
Have questions about building a similar React Native App? Reach out at devrel@pubnub.com.