I was facing issue in React Native when using react-native-pdf to display pdf in App
logs displayed in console:
Error: ReactNativeBlobUtil request error:
java.lang.IllegalStateException: Use of own trust manager but none
definedjava.lang.IllegalStateException: Use of own trust manager but
none defined]
Open Your code and simply use trustAllCerts props and set its value false
as shown below :
<Pdf
trustAllCerts={false}
source={{
uri: pdfUrl,
cache: true,
}}
onLoadComplete={(numberOfPages, filePath) => {
console.log(`Number of pages: ${numberOfPages}`);
}}
onPageChanged={(page, numberOfPages) => {
console.log(`Current page: ${page}`);
}}
onError={error => {
console.log(error);
}}
onPressLink={uri => {
console.log(`Link pressed: ${uri}`);
}}
style={styles.pdf}
/>
Related
I'm trying to use the YouTube player package in my React Native TypeScript mobile app but it's throwing an error and I cannot figure out how to fix this issue. I have researched a lot and installed some packages such as deprecated-react-native-prop-types and metro-react-native-babel-preset but still no luck.
In the Google Cloud Platform, I have enabled the YouTube Embedded Player API product in my project and created an API Key in it.
I'm running my application locally on the Android Studio Emulator and is using all the latest packages. Would that have anything to do with it?
My Code:
<YouTube
apiKey = "API KEY HERE"
videoId = "KVZ-P-ZI6W4"
play = {true}
fullscreen = {false}
loop = {false}
onReady={(e): void => { console.log(e); }}
onChangeState={(): void => { console.log(); }}
onChangeQuality={(): void => { console.log(); }}
onError={(e): void => { console.log(e); }}
style={{ alignSelf: 'stretch', height: 300 }}
/>
Error object return on onError:
{"error": "SERVICE_MISSING", "target": 235}
Error popup:
Get YouTube app:
This app won't run without the YouTube App, which is missing from your device.
I am trying to set up a face detector on expo.
First I import the package and set up the state hook:
import { Camera } from "expo-camera";
import * as FaceDetector from "expo-face-detector";
const [faces, setFaces] = useState([]);
And set up the onFacesDetected function:
const onFacesDetected = async ({ faces }) => {
setFaces(faces);
console.log({ faces });
};
And finally the camera:
<Camera
style={styles.camera}
ratio={"2:1"}
ref={(r) => {
camera = r;
}}
onFacesDetected={onFacesDetected}
faceDetectorSettings={{
mode: FaceDetector.Constants.Mode.fast,
detectLandmarks: FaceDetector.Constants.Landmarks.none,
runClassifications: FaceDetector.Constants.Classifications.all,
minDetectionInterval: 125,
tracking: false,
}}
>
But I am getting an error that the package doesnt provide the object needed (as in the docs tutorial):
[Unhandled promise rejection: TypeError: undefined is not an object (evaluating 'FaceDetector.Constants.Mode')]
I have tried reinstalling the package to no avail.
Any help on how to troubleshoot this is appreciated..
EDIT: in VSCode I see that Constants is not defined by hovering it. It shows this error:
Property 'Constants' does not exist on type 'typeof import("/home/david/Projects/adshare/node_modules/expo-face-detector/build/FaceDetector")'.
`
After looking in node_modules/expo-face-detector/ I was able to see that the functions were renamed in the latest version, but the docs have not been updated anywhere.
It is now:
faceDetectorSettings={{
mode: FaceDetector.FaceDetectorMode.fast,
detectLandmarks: FaceDetector.FaceDetectorLandmarks.none,
runClassifications: FaceDetector.FaceDetectorClassifications.all,
minDetectionInterval: 125,
tracking: false,
}}
I created a very simple page in react native. However, I'm getting the warning:
Warning: Unsafe legacy lifecycles will not be called for components using new component APIs.
%s uses %s but also contains the following legacy lifecycles:%s%s%s
The above lifecycles should be removed. Learn more about this warning here:
https://reactjs.org/blog/2018/03/27/update-on-async-rendering.html, Styled(PickerNB), getDerivedStateFromProps(), ,
UNSAFE_componentWillReceiveProps,
It is happening because the native-base Picker. If I remove the picker, I do not receive the warning.
...
class ChangeProperty extends Component {
constructor(props) {
super(props);
this.state = {
selectedProperty: '1'
};
}
componentDidMount() {
this.props.getProperties(); // It just loads a properties data from action component
}
onChangeProperty(value) {
this.setState({
selectedProperty: value
});
}
updatePropertyBTN = async () => {
await AsyncStorage.setItem('CurrentPropertyID', this.state.selectedProperty);
NavigationService.navigate('iRent');
}
...
<Picker
mode="dropdown"
iosHeader="Select Property"
placeholder="Property"
iosIcon={<Icon name="arrow-down" />}
selectedValue={this.state.selectedProperty}
textStyle={{ color: '#C0C0C0' }}
style={{ width: '100%' }}
onValueChange={(text) => this.onChangeProperty(text)}
>
{Object.keys(this.props.properties).map((key) => {
return (
<Picker.Item
label={this.props.properties[key]}
value={key}
key={key}
/>
);
})}
</Picker>
}
It is not causing any error in my code, but the warning message in the terminal is disturbing me because I do not know what is causing it.
Thanks
The warning is occurring because the NativeBase picker appears to be using legacy life cycle methods (eg componentWillReceiveProps like was mentioned in the warning) that are no longer supported by React - this has nothing to do with your code.
Ensure your NativeBase is updated to the latest package version and if it is you can raise an issue on their repo here
I’ve successfully managed to send a message from React Native (RN) to a WebView.
What I’m struggling with, is getting the message back from the WebView to RN. There’s no errors showing - it’s just that the message never gets through.
Here is the code which I’m using:
React Native Code
<WebView
ref={webview => (this.webview = webview)}
source={{ uri: "http://www.my-web-site"}}
onLoadEnd={() => this.onLoadEnd()}
onMessage={this.onMessage}
cacheEnabled={false}
originWhitelist={['*']}
javaScriptEnabled={true}
/>
onLoadEnd() {
this.webview.postMessage("RN message");
}
onMessage(message) {
console.log("I can’t see this message!");
}
WebView Code
document.addEventListener("message", function (event) {
setTimeout(function(){document.postMessage("WebView message")}, 3000);
}, false);
Please make sure that the data for each receiver is in and use the data that You need.
And always check the prescribed documents to see how to use parameters and grammar before using them.
RN
onLoadEnd() {
this.webview.postMessage("sendmessage");
}
onMessage(event) {
alert(event.nativeEvent.data);
}
WebView Code
document.addEventListener("message", function (event) {
window.postMessage(event.data);
});
React-native version 5.0 or later
window.ReactNativeWebView.postMessage(event.data);
Oh, at last, I finally came across the answer. It was a line of code which I had originally been trying to use to send a message from RN to the WebView. Turns out, it was the code required for sending from the WebView to RN:
WebView Code
document.addEventListener("message", function (event) {
window.ReactNativeWebView.postMessage(event.data);
}, false);
RN Code
<WebView onMessage={event => console.log(event.nativeEvent.data)} />
This works.
React Native
<WebView source={{ ... }}
containerStyle={{ ... }}
onMessage={ e => { console.log(e.nativeEvent.data) } }
/>
WebView
if(window.ReactNativeWebView) {
// send data object to React Native (only string)
window.ReactNativeWebView.postMessage(JSON.stringify(dataObject))
}
If you want to send complete object from webview to react-native android app then you need to stringify your object first
// Reactjs webapp
onClickSendObject = (item) => {
if(window.ReactNativeWebView) {
window.ReactNativeWebView.postMessage(JSON.stringify(item))
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
In react-native app use onMessage (for functional component)
<WebView
ref={webview => (this.webview = webview)}
source={{ uri: "give source url i.e your webapp link"}}
onMessage={m => onMessage(m.nativeEvent.data)} // functional component and for class component use (this.onMessage)
cacheEnabled={false}
originWhitelist={['*']}
javaScriptEnabled={true}
/>
// onMessage function
const onMessage = (m) => {
const messageData = JSON.parse(m);
console.log(messageData)
}
(window["ReactNativeWebView"] || window).postMessage('hello motiur dear','*');
I have done a sign in to my app using the native fetch API. I now need to load an image, so am loading it in a <WebView>, however the webview is not using the cookies from the fetch API outside of the webview. Is it possible to tell webview to use those cookies?
You can post a message containing your cookies content to your Webview using postMessage().
You need to get the ref of the Webview then post the message to your webview.
let webviewRef = null;
const cookiesContent = 'My cookies bla bla bla'
render() {
return (
<WebView
onLoad={() => webviewRef.postMessage(cookiesContent)}
ref={webview => { webviewRef = webview; }}
source={{ uri: 'https://YourUrl' }}
/>
);
}
Then in your Website you can create the cookies and use it
<script>
document.addEventListener("message", function(data) {
document.cookie=`cookiesName=${data.data}`;
});
</script>
If you aren't the owner of the website you can still try to inject the javascript with injectedJavaScript props of Webview Component.
const JsCode = 'document.addEventListener("message", function(data) {
document.cookie=`cookiesName=${data.data}`;
});';
<WebView
injectedJavaScript={JsCode}
onLoad={() => webviewRef.postMessage(cookiesContent)}
ref={webview => { webviewRef = webview; }}
source={{ uri: 'https://YourUrl' }}
/>
You can use https://github.com/react-native-community/cookies to get cookies and set them back