useURL hook expo-linking for background app - react-native

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().

Related

Expo-notifications background notification reception handling

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

How can I obtain a reference to the URL that was used to open my app with a link in iOS

I have a problem with the situation where my React Native Expo app is running in the background / inactive modus and the app is brought back to the foreground / active mode as a result of the user opening a deep link to my app from the mobile browser.
When this situation occurs, my app needs to get a reference to the deep link in order to show the expected content to the user. The problem is that Linking.getInitialURL() always returns the link that was used to open the app from cold start and not the link that was used to bring the app back to foreground / active modus.
Advice on how to fix this problem would be greatly appreciated.
Found it out by myself :-)
useEffect(() => {
Linking.addEventListener('url', handleLinkEvent);
return () => {
Linking.removeEventListener('url', handleLinkEvent);
};
}, []);
For these cases you should use Linking.addEventListener
To complete #timboektoe's answer, react-navigation offers a subscribe function to listen to any URL received.
const subscribe = (listener) => {
const onReceiveURL = ({ url }) => { listener(url); };
const subscription = Linking.addEventListener('url', onReceiveURL);
return () => {
subscription.remove();
};
};
const linking = {
prefixes,
config,
getInitialURL,
subscribe,
};

React Native websockets with hooks INVALID_STATE_ERR

React Native wont send multiple messages on state change throught websocket. Server recives 1st string normally and client gets console logs on every state change. Any idea why I get an error about state?
useEffect(() => {
socket.onopen = function (e) {
socket.send(String(state?.x));
};
socket.send("test") <-- this one does not work
console.log("send")
socket.onmessage = function () {
console.log("message")
}
socket.close();
}, [state])
Returns error INVALID_STATE_ERR
So basically when using react native with EXPO you will get those errors. After the application is build and installed (on the same phone) the application works.

TypeError Object is not a constructor (evaluating new_pubnubReact.default')

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>
}

How to detect screenshots with React Native (both Android and iOS)

I am trying to detect if a user takes a screenshot while using a smartphone app that I have built. I am building my project with React Native.
I have been told that I can possibly prevent screenshots for Android but not for iOS. but can I still detect whether a user attempts to take a screenshot so that I can at least send a warning via Alert?
Thanks in advance
I tried react-native-screenshot-detector but it did not work
you can use this package it supports android&ios screenshot detecting react-native-detector
import {
addScreenshotListener,
removeScreenshotListener,
} from 'react-native-detector';
// ...
React.useEffect(() => {
const userDidScreenshot = () => {
console.log('User took screenshot');
};
const listener = addScreenshotListener(userDidScreenshot);
return () => {
removeScreenshotListener(listener);
};
}, []);
There is no package for it currently.