I am using expo-notifications package in react native (expo) to handle incoming notifications. I am getting notification correctly when the app is in background and foreground - for sending notifications I am using 'expo-server-sdk' package in the backend. I can handle foreground notification reception using addNotificationReceivedListener() function from expo-notification package.For handling background notification reception in the expo documentation (link: - https://docs.expo.dev/versions/latest/sdk/notifications/#handling-incoming-notifications-when-the-app-is-1) they are saying we can use expo-task-manager library to handle it. The code that i have written by referring expo documentation is given below.
...
import * as Notifications from 'expo-notifications';
import * as TaskManager from 'expo-task-manager';
...
//This code is written in root file and outside any react component
const BACKGROUND_NOTIFICATION_TASK = 'BACKGROUND-NOTIFICATION-TASK';
TaskManager.defineTask(
BACKGROUND_NOTIFICATION_TASK,
({ data, error, executionInfo }) =>{
if(error){
console.log('error occurred');
}
if(data){
console.log('data-----',data);
}
})
//This code is written in App.js root component
useEffect(() => {
Notifications.registerTaskAsync(BACKGROUND_NOTIFICATION_TASK);
return()=>{
Notifications.unregisterTaskAsync(BACKGROUND_NOTIFICATION_TASK);
}
},[])
Also in the expo documentation. they say that this background task will not work with expo go app. so O executed expo run:android and build the app into my physical android device. Even After doing all this, When a notification arrives this task is not running and I am not getting any output in the console log from the code console.log('data-----',data); neither getting output for the code console.log('error occurred'); which means 'BACKGROUND-NOTIFICATION-TASK' is not getting executed when notification comes when app is in background. Can anyone please tell me what the problem is?
Basically, the only mistake you made was to call
Notifications.registerTaskAsync(BACKGROUND_NOTIFICATION_TASK)
inside useEffect which I am guessing is inside a react component, this code must be written outside the react component as you did with TaskManager.defineTask...
Take a look at this simple App.js example for further clarity
import { StyleSheet, View } from "react-native";
import * as Notifications from "expo-notifications";
import * as TaskManager from "expo-task-manager";
const BACKGROUND_NOTIFICATION_TASK = "BACKGROUND-NOTIFICATION-TASK";
TaskManager.defineTask(
BACKGROUND_NOTIFICATION_TASK,
({ data, error, executionInfo }) => {
if (error) {
console.log("error occurred");
}
if (data) {
console.log("data-----", data);
}
}
);
Notifications.registerTaskAsync(BACKGROUND_NOTIFICATION_TASK);
export default function App() {
return <View style={styles.container}></View>;
}
const styles = StyleSheet.create({
container: {
flex: 1
},
});
No need for useEfect
Related
The expo-linking React Native package has a hook named useURL that isn't working for me when the app is in the background. From the docs it Returns the initial URL followed by any subsequent changes to the URL. The problem I'm having with my managed expo app is that the hook doesn't work when the app is already open in the background. Here is the hook:
export default function App() {
const isLoadingComplete = useCachedResources();
const url = Linking.useURL();
useEffect(() => {
Alert.alert(url ? url.substring(20) : 'null');
}, [url]);
if (!isLoadingComplete) {
return null;
} else {
return (
...
);
}
}
If I open the URL exp://exp.host/#myprofile/myproject?a=bwhen the app is closed, I get an Alert as expected. If the app is in the background, the Alert doesn't go off. I've tested on an iOS emulator and a physical Android. Any solutions? Note that similar problems happen with Linking.addEventListener().
I am using react-native-audio-recorder-player to record and play audio. IF I close app while audio is being played, Audio is still playing. But In fact I called stopAudio() in componentWillUnmount(). But I noticed that componentWillUnmount() is not getting called when app is closed.
I would like to know two things that
1.Will componentWillUnmount() be called when app is closed? If not
2.Is there any way to know programmatically that app is closed?
You can't use componentWillUnmount() for this case, this function is not called when the application is closed.
I think you can use react native appstate
Or you can use custom hook to stop audio click here
import React from 'react';
import { Text, View } from 'react-native';
import useAppState from 'react-native-appstate-hook';
export default function App() {
const { appState } = useAppState({
onChange: (newAppState) => console.warn('App state changed to ', newAppState),
onForeground: () => console.warn('App went to Foreground'),
onBackground: () => stopAudio(),
});
return <View/>
}
I have created an react-native/typescript app with expo CLI, this generate some base code, inlcuding hooks/useCachedResources to load any resources or data that we need prior to rendering the app, in my case in this hook I load custom fonts(in particular Inter Display Font). I'm experimenting some problems because the app loads only two weights: regular and medium, If I try to use semi-bold or bold this doesnt work and use the san serif font that comes by default.
Additional data:
The fonts path its ok
Expo app doesn't show any error. I have seen in other questions errors such as fontFamily "MyFontFamily" is not a system font and has not been loaded through Font.loadAsync. This is not the case.
Font family name is in the correct format.
I'm using React Native UI Kitten and I load the fonts as they suggest in Advanced Configuration and change some especific styles.
According to some answers The out of the box support for custom fonts on Android is a little limited in React Native. It does not support font weights other than normal and bold. So I tried setting fontWeight: normal or any of the weights but nothing works.
useCachedResources hook
This come by default with expo init my-app.
import * as Font from 'expo-font';
import * as SplashScreen from 'expo-splash-screen';
import { useEffect, useState } from 'react';
// Error reporting service
import { logger } from '#utils';
export function useCachedResources(): boolean {
const [isLoadingComplete, setLoadingComplete] = useState(false);
// Load any resources or data that we need prior to rendering the app
useEffect(() => {
async function loadResourcesAndDataAsync() {
try {
await SplashScreen.preventAutoHideAsync();
// Load fonts
await Font.loadAsync({
'inter-display-regular': require('../assets/fonts/InterDisplay-Regular.ttf'),
'inter-display-medium': require('../assets/fonts/InterDisplay-Medium.ttf'),
'inter-display-semibold': require('../assets/fonts/InterDisplay-SemiBold.ttf'),
'inter-display-bold': require('../assets/fonts/InterDisplay-Bold.ttf'),
});
} catch (loadCachedResourcesError) {
logger.log(loadCachedResourcesError);
} finally {
setLoadingComplete(true);
await SplashScreen.hideAsync();
}
}
loadResourcesAndDataAsync();
}, []);
return isLoadingComplete;
}
Consuming the hook in App.tsx
import { StatusBar } from 'expo-status-bar';
import React from 'react';
import { SafeAreaProvider } from 'react-native-safe-area-context';
import useCachedResources from './hooks/useCachedResources';
import Navigation from './navigation';
// again this comes by defautl expo init command
export default function App(): React.ReactElement | null {
const isLoadingComplete = useCachedResources();
if (!isLoadingComplete) {
return null;
}
return (
<SafeAreaProvider>
<Navigation />
<StatusBar />
</SafeAreaProvider>
);
}
mapping.json: specific UI-Kitten configuration to change font style
I can think that the problem comes from here but the thing is, if there was a problem loading the fonts, either expo would have already thrown an error or the other fonts weights(regular/medium) would not load.
{
"strict": {
"text-font-family": "inter-display-regular",
"text-heading-1-font-size": 32,
"text-heading-1-font-weight": "normal",
"text-heading-1-font-family": "inter-display-medium",
"text-paragraph-1-font-size": 16,
"text-paragraph-1-font-weight": "normal",
"text-paragraph-1-font-family": "$text-font-family",
}
}
The problem
I have no idea if the problem comes from expo, ui kitten or if inter font can't be loaded by react native by some other reason.
In your useCachedResources try to remove 'await' keyword from SplashScreen method's:
SplashScreen.preventAutoHideAsync();
SplashScreen.hideAsync();
I am new to react native and am trying to create push notifications for android.
I am using the following tutorial from PubNub.
PubNub tutorial
When I run my app in the android studio emulator after finishing the tutorial I get the following error.
Not quite sure what it means of how to fix it as when I google the problem nothing comes up.
Here is my code
import React from 'react';
import PushNotificationIOS from 'react-native';
import PubNubReact from 'pubnub-react';
const PushNotification = require('react-native-push-notification');
export default class App extends React.Component {
constructor(props) {
super(props);
this.pubnub = new PubNubReact({
publishKey: 'YOUR_PUBNUB_PUBLISH_KEY_HERE',
subscribeKey: 'YOUR_PUBNUB_SUBSCRIBE_KEY_HERE'
});
this.pubnub.init(this);
PushNotification.configure({
// Called when Token is generated.
onRegister: function(token) {
console.log( 'TOKEN:', token );
if (token.os == "ios") {
this.pubnub.push.addChannels(
{
channels: ['notifications'],
device: token.token,
pushGateway: 'apns'
});
// Send iOS Notification from debug console: {"pn_apns":{"aps":{"alert":"Hello World."}}}
} else if (token.os == "android"){
this.pubnub.push.addChannels(
{
channels: ['notifications'],
device: token.token,
pushGateway: 'gcm' // apns, gcm, mpns
});
// Send Android Notification from debug console: {"pn_gcm":{"data":{"message":"Hello World."}}}
}
}.bind(this),
// Something not working?
// See: https://support.pubnub.com/support/solutions/articles/14000043605-how-can-i-troubleshoot-my-push-notification-issues-
// Called when a remote or local notification is opened or received.
onNotification: function(notification) {
console.log( 'NOTIFICATION:', notification );
// Do something with the notification.
// Required on iOS only (see fetchCompletionHandler docs: https://reactnative.dev/docs/pushnotificationios)
// notification.finish(PushNotificationIOS.FetchResult.NoData);
},
// ANDROID: GCM or FCM Sender ID
senderID: "sender-id",
});
}
}
pubnub-react library has been completely changed in version 2.0.0. It no longers includes pubnub JavaScript SDK by default so you have to install it as well.
Here is the link to new PubNub React repository, and in the README.md file you can find examples on how to use it.
If you want to use the older version that is compatible with the tutorial/blog post you may be reading, please install the older version of the PubNub React SDK like so:
$ npm install pubnub-react#1
To summarize the changes, pubnub-react now uses Context and Hooks API to propagate PubNub instance deep into the children tree.
Provider
You need to include the provider somewhere top in the component tree.
import React from 'react'
import PubNub from 'pubnub'
import { PubNubProvider } from 'pubnub-react'
const pubnub = new PubNub({}) // PubNub configuration
export const App = () => {
return <PubNubProvider client={pubnub}>
<Child />
</PubNubProvider>
}
Consumer
To use the PubNub instance somewhere else, you can now just use the usePubNub hook.
import { usePubNub } from 'pubnub-react'
export const Child = () => {
const pubnub = usePubNub()
return <div>I am using PubNub!</div>
}
Im using
React Native Push Notification https://github.com/zo0r/react-native-push-notification
How can I pass my pushMessage(chat) into the notification?
I have this onNotification and PushNotificationIOS error when received push message from server.
error on device
which part should I work on?
ps: im not understand how this work -> notification.finish(PushNotificationIOS.FetchResult.NoData);
App.js
--------
PushNotification.configure({
// (required) Called when a remote or local notification is opened or received
onNotification: function(notification) {
console.log( 'NOTIFICATION:', notification );
// process the notification
// required on iOS only (see fetchCompletionHandler docs: https://facebook.github.io/react-native/docs/pushnotificationios.html)
notification.finish(PushNotificationIOS.FetchResult.NoData);
},
});
class App extends Component{
componentDidMount(){
const connection = signalr.hubConnection('https://api.abc.com');
const proxy = connection.createHubProxy('chatHub');
proxy.on('pushMessage', (chat) => {
PushNotification.localNotificationSchedule({
message: "My Notification 1",
date: new Date(Date.now())
});
});
}
}
PushNotificationIOS is an API provided by react-native so maybe you import it from react-native like so
import { PushNotificationIOS } from 'react-native'
PushNotification uses PushNotificationIOS. You have to add and import it.
Do the following.
In the console, run this if using Yarn: yarn add #react-native-community/push-notification-ios...
... or run this if using NPM: npm install #react-native-community/push-notification-ios
Then, in your file where you use PushNotification, add this line among your other imports:
import PushNotificationIOS from "#react-native-community/push-notification-ios"