React Native EXPO AdMobInterstitial ads not working properly, The ads showing only one time when I click on the page - react-native

In my app, all other Expo AdMob ads are working very well except AdMobInterstitial. AdMobInterstitial ads showing only once. when I try to visit the next time on that page the ads not showing. I am not getting any errors as well. could you please tell me what's wrong with the below codes? Appreciate your support.
I am using this-> npm i expo-ads-admob
import React, { useEffect, useState, } from 'react';
import { Text, View } from 'react-native';
import {
AdMobBanner,
AdMobInterstitial,
PublisherBanner,
AdMobRewarded,
setTestDeviceIDAsync,
} from 'expo-ads-admob';
const interstitial = async () => {
await AdMobInterstitial.setAdUnitID('ca-app-pub-3940256099942544/1033173712');
try {
await AdMobInterstitial.requestAdAsync({ servePersonalizedAds: true});
await AdMobInterstitial.showAdAsync();
} catch (error) {
console.log(e);
}
}
const TestAds = ({ navigation }) =>{
useEffect (() => {
interstitial();
},[])
return (
<View>
<Text>Hello World Testing</Text>
</View>
});
export default TestAds;

Related

How to play audio from server use expo-av in react-native

I try to play video from server. This is my code:
import React, {useState, useEffect} from 'react';
import { Button } from 'react-native';
import { Audio } from 'expo-av';
export default function App() {
const [audioStatus, setAudioStatus] = useState(false)
const [sound, setSound] = useState(new Audio.Sound());
useEffect(()=>{
(async () => {
console.log('status', audioStatus)
if (audioStatus) {
await sound.loadAsync('https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3')
try {
await sound.playAsync()
} catch (e) {
console.log(e)
}
}else {
await sound.stopAsync()
await sound.unloadAsync()
}
})()
},[audioStatus])
return (
<Button color={audioStatus ? 'red' : 'green'} title={'play'} onPress={()=>setAudioStatus(!audioStatus)} />
);
}
And I get error:
LOG status false
WARN Possible Unhandled Promise Rejection (id: 15):
Error: Cannot complete operation because sound is not loaded.
http://192.168.100.60:19000/node_modules/expo/AppEntry.bundle?platform=android&dev=true&hot=false:100133:28
generatorResume#[native code]
asyncGeneratorStep#http://192.168.100.60:19000/node_modules/expo/AppEntry.bundle?platform=android&dev=true&hot=false:20982:26
It looks like your post is mostly code; please add some more details.It looks like your post is mostly code; please add some more details.

React Native Expo CLI Import .ttf Fonts

Trying to import .ttf for font in expo cli.
I also have splash screen. I wanna show the splash screen until the font loads.
Font: Josefin Sans.
"expo": "~45.0.0"
I took reference from following links but nothing works:
Using Custom Fonts: https://docs.expo.dev/guides/using-custom-fonts/
Splash Screen: https://docs.expo.dev/versions/latest/sdk/splash-screen/
Code (App.js)
import { useState, useEffect, useCallback } from "react";
import { Text } from "react-native";
import { SafeAreaView } from "react-native-safe-area-context";
import { StatusBar } from "expo-status-bar";
import Header from "./components/Header.component";
import styles from "./styles/appStyle";
import * as Font from "expo-font";
import * as SplashScreen from "expo-splash-screen";
const App = () => {
const [appIsReady, setAppIsReady] = useState(false);
useEffect(() => {
async function prepare() {
try {
// Pre-load fonts
await Font.loadAsync({
"JosefinSans-Regular": require("./assets/fonts/JosefinSans-Regular.ttf"),
});
// Artificially delay for two seconds to simulate a slow loading
// experience. Please remove this if you copy and paste the code!
await new Promise((resolve) => setTimeout(resolve, 2000));
} catch (e) {
} finally {
// Tell the application to render
setAppIsReady(true);
}
}
prepare();
}, []);
const onLayoutRootView = useCallback(async () => {
if (appIsReady) {
// This tells the splash screen to hide immediately! If we call this after
// `setAppIsReady`, then we may see a blank screen while the app is
// loading its initial state and rendering its first pixels. So instead,
// we hide the splash screen once we know the root view has already
// performed layout.
await SplashScreen.hideAsync();
}
}, [appIsReady]);
if (!appIsReady) {
return null;
}
return (
<>
<SafeAreaView style={styles.container} onLayout={onLayoutRootView}>
<Header />
<Text>Hello World!</Text>
<StatusBar style="light" backgroundColor="#05060B" />
</SafeAreaView>
</>
);
};
export default App;
Error
Android Bundling failed 12ms
Unable to resolve module ./assets/fonts/JosefinSans-Regular.ttf from C:\Users\user\Desktop\app\App.js:
None of these files exist:
* JosefinSans-Regular.ttf
* assets\fonts\JosefinSans-Regular.ttf\index(.native|.android.ts|.native.ts|.ts|.android.tsx|.native.tsx|.tsx|.android.js|.native.js|.js|.android.jsx|.native.jsx|.jsx|.android.json|.native.json|.json)
18 | // Pre-load fonts
19 | await Font.loadAsync({
> 20 | "JosefinSans-Regular": require("./assets/fonts/JosefinSans-Regular.ttf"),
| ^
21 | });
22 | // Artificially delay for two seconds to simulate a slow loading
23 | // experience. Please remove this if you copy and paste the code!
File Structure:
Snap.png
Answer
expo install #expo-google-fonts/josefin-sans expo-font
And the code looks like this.
import { useState, useEffect, useCallback } from "react";
import { Text } from "react-native";
import { SafeAreaView } from "react-native-safe-area-context";
import { StatusBar } from "expo-status-bar";
import Header from "./components/Header.component";
import styles from "./styles/appStyle";
import * as Font from "expo-font";
import * as SplashScreen from "expo-splash-screen";
import {
useFonts,
JosefinSans_100Thin,
JosefinSans_200ExtraLight,
JosefinSans_300Light,
JosefinSans_400Regular,
JosefinSans_500Medium,
JosefinSans_600SemiBold,
JosefinSans_700Bold,
JosefinSans_100Thin_Italic,
JosefinSans_200ExtraLight_Italic,
JosefinSans_300Light_Italic,
JosefinSans_400Regular_Italic,
JosefinSans_500Medium_Italic,
JosefinSans_600SemiBold_Italic,
JosefinSans_700Bold_Italic,
} from "#expo-google-fonts/josefin-sans";
const App = () => {
const [appIsReady, setAppIsReady] = useState(false);
let [fontsLoaded] = useFonts({
JosefinSans_100Thin,
JosefinSans_200ExtraLight,
JosefinSans_300Light,
JosefinSans_400Regular,
JosefinSans_500Medium,
JosefinSans_600SemiBold,
JosefinSans_700Bold,
JosefinSans_100Thin_Italic,
JosefinSans_200ExtraLight_Italic,
JosefinSans_300Light_Italic,
JosefinSans_400Regular_Italic,
JosefinSans_500Medium_Italic,
JosefinSans_600SemiBold_Italic,
JosefinSans_700Bold_Italic,
});
const prepare = async () => {
try {
// Pre-load fonts
await Font.loadAsync(fontsLoaded)
.then(() => {
setAppIsReady(true);
})
.catch((err) => {});
// Artificially delay for two seconds to simulate a slow loading
// experience. Please remove this if you copy and paste the code!
// await new Promise((resolve) => setTimeout(resolve, 2000));
} catch (e) {}
};
useEffect(() => {
prepare();
}, []);
const onLayoutRootView = useCallback(async () => {
if (appIsReady) {
// This tells the splash screen to hide immediately! If we call this after
// `setAppIsReady`, then we may see a blank screen while the app is
// loading its initial state and rendering its first pixels. So instead,
// we hide the splash screen once we know the root view has already
// performed layout.
await SplashScreen.hideAsync();
}
}, [appIsReady]);
if (!appIsReady) {
return null;
}
return (
<>
<SafeAreaView style={styles.container} onLayout={onLayoutRootView}>
<Header />
<Text>Hello World!</Text>
<StatusBar style="light" backgroundColor="#05060B" />
</SafeAreaView>
</>
);
};
export default App;

expo run:android is stuck at blank white screen

As seen in the above image, after successfully building for android, the standalone app is installed on the device but when opened, before showing the Splash screen, the blank white screen appears.
This is my App.js code
import React, { useState, useEffect, useRef } from "react";
import { NavigationContainer } from "#react-navigation/native";
import StackNavigator from "./StackNavigator";
import { AuthProvider } from "./hooks/useAuth";
import { ActivityIndicator, LogBox, View } from "react-native";
import { Asset } from "expo-asset";
import {
Roboto_100Thin,
Roboto_100Thin_Italic,
Roboto_300Light,
Roboto_300Light_Italic,
useFonts,
} from "#expo-google-fonts/roboto";
import AppLoading from "expo-app-loading";
import * as Font from "expo-font";
import * as encoding from "text-encoding";
LogBox.ignoreAllLogs();
function cacheImages(images) {
return images.map((image) => {
if (typeof image === "string") {
return Image.prefetch(image);
} else {
return Asset.fromModule(image).downloadAsync();
}
});
}
function cacheFonts(fonts) {
return fonts.map((font) => Font.loadAsync(font));
}
export default function App() {
const [ready, setReady] = useState(true);
let [fontsLoaded] = useFonts({
"Roboto-Thin": Roboto_100Thin,
Roboto_100Thin_Italic,
"Roboto-Light": Roboto_300Light,
Roboto_300Light_Italic,
});
async function _loadAssetsAsync() {
const imageAssets = await cacheImages([
require("./ASSETS/Loading_Black.gif"),
require("./ASSETS/icons/like.png"),
require("./ASSETS/icons/like-red.png"),
require("./ASSETS/icons/comment.png"),
require("./ASSETS/icons/share.png"),
require("./ASSETS/CHAT_BGRD-02.jpeg"),
]);
await Promise.all([...imageAssets, fontsLoaded]);
}
return ready && fontsLoaded ? (
<NavigationContainer>
<AuthProvider>
<StackNavigator />
</AuthProvider>
</NavigationContainer>
) : (
<AppLoading
startAsync={_loadAssetsAsync}
onFinish={() => setReady(true)}
onError={(e) => {
console.log(e);
}}
/>
);
}
The app is perfectly running on development mode, production mode, and even tried using
expo start --no-dev --minify
All these are perfectly working fine. But if I try to run the app in standalone mode, this is what's the output is. Appreciate your help :)
I had this happen, I updated android studio, updated android studio's sdk tools: Android emulator, hypervisor, platform tools, etc.
Then I re-made the devices in the Virtual Device Manager and then re-ran "expo start --android" and it worked.

Expo: How to detect when a WebBrowser instance is closed by the user?

I have an Expo app that will open some web page with a redirect to expo itself. On that case, this is to perform 3DS callbacks. Here is a very simplified version:
import React, {
FC, useEffect, useState,
} from 'react';
import * as Linking from 'expo-linking';
import * as WebBrowser from 'expo-web-browser';
import {
Button,
} from '#private/apps-components';
import {
ButtonProps,
View,
} from 'react-native';
export const MyComponent: FC = () => {
const [loading, setLoading] = useState<boolean>(false);
const urlEventHandler = async (event): Promise<void> => {
console.log('url-event', event);
setLoading(false);
// Stuff...
};
useEffect(() => {
Linking.addEventListener('url', urlEventHandler);
return () => Linking.removeEventListener('url', urlEventHandler);
}, []);
const handlePress: ButtonProps['onPress'] = () => {
setLoading(false);
WebBrowser.openBrowserAsync(aRandomUrlThatWillRedirectToTheApp, {
showInRecents: true,
})
}
return (
<View>
<Button
title="Test"
onPress={handlePress}
loading={loading}
/>
</View>
);
};
export default null;
This is working. However, if the customer close the navigator before the web redirect is being processed, the app is stuck on the loading state.
The question is: How to detect if a user has closed the opened WebBrowser?
Solved this using AppState:
https://reactnative.dev/docs/appstate
if (appState === "active") { // do things after closing the browser }
I haven't actually tested this - could follow up - but you could probably use react-navigation to detect whether the component is in focus or not. IE when you open the web browser, the component is not in focus, but when you close the web browser, the component is back in focus.
For react navigation version 4 you would wrap the component in withNavigationFocus in order to achieve this: https://reactnavigation.org/docs/4.x/function-after-focusing-screen#triggering-an-action-with-the-withnavigationfocus-higher-order-component. For 5, and 5+, you can use the useIsFocused hook: https://reactnavigation.org/docs/5.x/function-after-focusing-screen/#re-rendering-screen-with-the-useisfocused-hook

Expo Audio.Recording Cannot read property 'uri' of undefined

I'm trying to start a new recording in Expo react native but for some odd reason the app crashes.
The code i written is pretty much copy paste from the official expo docs.
import React, { useState, useEffect } from 'react';
import { Audio } from 'expo-av';
import PitchFinder from "pitchfinder";
import { StyleSheet, Text, View, Button } from 'react-native';
const Tuner = () => {
const pitchFinder = new PitchFinder.YIN();
const start = async () => {
const recording = new Audio.Recording();
console.log(recording)
await recording.prepareToRecordAsync(Audio.RECORDING_OPTIONS_PRESET_HIGH_QUALITY);
await recording.startAsync();
const audio_stream = recording.getURI();
console.log(audio_stream);
await recording.stopAndUnloadAsync();
}
return (
<View>
<Button title="Start recording" onPress={() => start()} />
</View>
)
};
export default Tuner;
The app crashes at await recording.prepareToRecordAsync(Audio.RECORDING_OPTIONS_PRESET_HIGH_QUALITY);
with the error
Unhandled Rejection (TypeError): Cannot read property 'uri' of undefined
please check Expo documentation again
check permission
https://docs.expo.io/versions/latest/sdk/audio/
try with
const recording = new Audio.Recording();
try {
await recording.prepareToRecordAsync(Audio.RECORDING_OPTIONS_PRESET_HIGH_QUALITY);
await recording.startAsync();
// You are now recording!
} catch (error) {
// An error occurred!
}