I want to read phone sms using expo react-native, I'm sending request to read sms permission and nothing is happening.
When I click the button it's not opening the alert modal
here is my code:
import 'react-native-gesture-handler';
import '#babel/helper-skip-transparent-expression-wrappers'
import { StatusBar } from 'expo-status-bar';
import React,{useState,useEffect,useRef} from 'react';
import { StyleSheet, Text, View,Button } from 'react-native';
import RootStackScreen from './android/screens/RootStackScreen'
import { NavigationContainer } from '#react-navigation/native';
import { Alert, PermissionsAndroid } from 'react-native';
export default function App() {
async function requestSmsPermission() {
try {
const granted = await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.READ_SMS,
{
title: 'My App SMS Permission',
message:
'My App needs access to your SMS messages ' +
'so you can read them in the app.',
buttonNeutral: 'Ask Me Later',
buttonNegative: 'Cancel',
buttonPositive: 'OK',
},
);
if (granted === PermissionsAndroid.RESULTS.GRANTED) {
console.log('You can read SMS messages');
} else {
console.log('SMS permission denied');
}
} catch (err) {
console.log(err);
}
}
return (
<>
<View style={{marginTop: 200}}></View>
<Button
title="Request SMS Permission"
onPress={requestSmsPermission}
style={{marginTop: 400}}
/>
</>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
});
I want the codes to ask user permission to read sms using expo, react-native
Related
SOLVED!: Check the one reply below. It solves it. But, after you allow camera, when you click the button again, it won't prompt again, which is natural. You have to deny camera from the emulator or phone's settings again for it to prompt again.
I am basically trying to do this: a button, when clicked; it will prompt the user of camera permission, in react. In my current app here, it asks on first launch of the app. I tried various ways to implement it with button, but to no avail. But this code works, without error. Here is my app.js:
import React, {Component} from 'react'
import {StyleSheet, View, Text, Button} from 'react-native'
import {Permission, PERMISSION_TYPE} from 'D:/Reactdeneme/reacttest/src/AppPermission'
export default class App extends Component {
componentDidMount() {
Permission.checkPermission(PERMISSION_TYPE.camera)
//this the thing that prompts the camera permission. I want this in a button.
}
render() {
return (
<View style={styles.container}>
<Text style={{fontSize: 30}}>izinler</Text>
</View>
)
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center'
}
})
THIS PART IS PROBABLY OPTIONAL, so please don't be afraid of the long code blocks. Here is my AppPermissions.js aswell:
import {check, request, PERMISSIONS, RESULTS} from 'react-native-permissions';
import {Platform} from 'react-native'
const PLATFORM_CAMERA_PERMISSIONS= {
ios:PERMISSIONS.IOS.MICROPHONE,
android: PERMISSIONS.ANDROID.CAMERA
}
const REQUEST_PERMISSION_TYPE = {
camera: PLATFORM_CAMERA_PERMISSIONS
}
const PERMISSION_TYPE= {
camera: 'camera'
}
class AppPermission {
checkPermission= async (type): Promise<boolean> => {
console.log("AppPermission checkPermission type:", type)
const permissions = REQUEST_PERMISSION_TYPE[type][Platform.OS]
console.log("AppPermission checkPermission permissions:", permissions)
if(!permissions){
return true
}
try {
const result = await check(permissions)
console.log("AppPermission checkPermission result:", result)
if (result === RESULTS.GRANTED) return true
return this.requestPermission(permissions)
} catch (error) {
console.log("AppPermission checkPermission error:", error)
return false
}
}
requestPermission=async(permissions): Promise<boolean> => {
console.log("AppPermission requestPermission permissions:", permissions)
try {
const result = await request(permissions)
console.log("AppPermission requestPermission result:", result)
return result === RESULTS.GRANTED
}catch(error) {
console.log("AppPermission requestPermission error:", error)
return false
}
}
}
const Permission = new AppPermission()
export {Permission, PERMISSION_TYPE}
You should read more react-native docs.
Remove checkPermission in componentDidMount and add this to onPress props of Button.
import React, {Component} from 'react'
import {StyleSheet, View, Text, Button} from 'react-native'
import {Permission, PERMISSION_TYPE} from 'D:/Reactdeneme/reacttest/src/AppPermission'
export default class App extends Component {
checkPermission = () => {
Permission.checkPermission(PERMISSION_TYPE.camera);
}
render() {
return (
<View style={styles.container}>
<Text style={{fontSize: 30}}>izinler</Text>
<Button title="Check" onPress={this.checkPermission}/>
</View>
)
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center'
}
})
when i press the sign in with google button it doesn't do anything
i followed https://docs.expo.io/versions/latest/sdk/google/
the iosClientId: 'my-id', is normally my google clientid but changed it for security reasons
import React, { Component } from 'react';
import {StyleSheet, Text, View, Button} from 'react-native';
class LoginScreen extends Component {
async signInWithGoogleAsync () {
try {
const result = await Expo.Google.logInAsync({
//androidClientId: YOUR_CLIENT_ID_HERE,
behavior: 'web',
iosClientId: 'my-id',
scopes: ['profile', 'email'],
});
if (result.type === 'success') {
return result.accessToken;
} else {
return { cancelled: true };
}
} catch (e) {
return { error: true };
}
}
render() {
return (
<View style={styles.container}>
<Button title={"Sign In With Google"}
onpress={() =>this.signInWithGoogleAsync()}
/>
</View>
);
}
}
export default LoginScreen;
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF'
}
});
I expect is when i press the Sign In With Google button it to let me sign in
but what im getting is the button not doing anything
Change your render function to this:
render() {
return (
<View style={styles.container}>
<Button title={"Sign In With Google"}
onPress={() =>this.signInWithGoogleAsync()}
/>
</View>
);
}
I am making a react native application where the user logs in with Facebook and then goes to their home page with more details of the app and I can not get the App to navigate to the homepage after successful login with Facebook.
I'm using React Navigator. I have been searching Stackoverflow for 3 days with no luck...
Any help would be appreciated
the homepage successfully navigated when using the regular button
as shown above but it will not after the facebook authentication
//index.js
import React, {
Component
} from 'react';
import {
Platform,
StyleSheet,
Image,
Button,
Slider,
Text,
View,
Dimensions
} from 'react-native';
import FBLoginButton from '../FBLoginButton';
import {
SliderBox
} from 'react-native-image-slider-box';
import {
SafeAreaView
} from 'react-navigation';
import A from 'react-native-a'
import {
NavigationActions,
StackActions
} from 'react-navigation';
import {
createStackNavigator,
createAppContainer
} from 'react-navigation';
//import App from '../App';
const FBSDK = require('react-native-fbsdk');
const {
LoginManager,
} = FBSDK;
let isLoggedIn = false
type Props = {};
export default class Login extends Component < Props > {
constructor(props) {
//this._loginAuth = this._loginAuth.bind(this)
super(props);
this.state = {
images: [
'https://hluhluwegamereserve.com/wp-content/uploads/2014/03/IMG_1579.jpg',
'https://static.independent.co.uk/s3fs-public/thumbnails/image/2019/04/26/09/giraffe.jpg',
]
};
}
//this.props.navigation.push('Home')
render() {
LoginManager.logInWithReadPermissions(['public_profile']).then(
function(result) {
if (result.isCancelled) {
alert('Login was cancelled');
} else {
alert('Login was successful with permissions: ' + result.grantedPermissions.toString());
//this.props.navigation.push('Home')
//this.props.navigation.navigate("Home")
//this._loginAuth()
}
},
function(error) {
alert('Login failed with error: ' + error);
}
);
//alert(this.state.loggedIn)
return (
<
View style = {
styles.container
} >
<
SliderBox style = {
styles.slider
}
images = {
this.state.images
}
sliderBoxHeight = {
'100%'
}
paginationBoxVerticalPadding = {
0
}
//parentWidth={400}
/>
<
Button onPress = {
() => this.props.navigation.navigate('Home')
}
title = "Go to Home"
color = "#841584" /
>
<
FBLoginButton onload = {
() => this.props.navigation.navigate('Home')
}
style = {
styles.welcome
} >
<
/FBLoginButton>
<
Text style = {
styles.instructions
} >
<
/Text>
<
/View>
);
}
}
if (this.isLoggedIn) {
this.props.navigation.navigate('Home')
}
// ...
// Attempt a login using the Facebook login dialog,
// asking for default permissions.
const styles = StyleSheet.create({
container: {
flex: 1,
//padding: 40,
//marginBottom: 250,
justifyContent: 'center',
alignItems: 'center',
//marginTop: '15%',
paddingTop: '15%',
paddingBottom: '15%',
resizeMode: 'contain',
},
slider: {
//width: '100%',
//alignSelf: 'flex-start',
//width: this.deviceWidth,
resizeMode: 'contain',
},
welcome: {
fontSize: 12,
textAlign: 'center',
marginBottom: '10%',
padding: '5%',
//paddingTop: 40,
},
terms: {
fontSize: 12,
color: 'blue',
textAlign: 'center',
margin: 1,
},
instructions: {
textAlign: 'center',
color: '#333333',
//marginBottom: 5,
},
safeArea: {
backgroundColor: '#ddd'
},
});
Here is my App.Js
//App.js
/*
* #format
* #flow
*/
import React, {
Component
} from 'react';
import {
Platform,
StyleSheet,
Image,
Button,
Slider,
Text,
View,
Dimensions
} from 'react-native';
import A from 'react-native-a'
import {
NavigationActions,
StackActions
} from 'react-navigation';
import {
createStackNavigator,
createAppContainer
} from 'react-navigation';
import HomeScreen from './screens/HomeScreen';
import Login from './screens/Login';
import {
StackNavigator
} from "react-navigation";
import FBLoginButton from './FBLoginButton'
type Props = {};
//Login Screen
const NavigationApp = createStackNavigator({
Login: Login,
Home: HomeScreen
}, {
initialRouteName: "Login"
});
class App extends Component < Props > {
constructor(props) {
super(props);
}
render() {
return (
//Empty View For App.js
<
View >
<
/View>
);
}
}
//Navagation Goes To Login.js For Default
export default createAppContainer(NavigationApp);
Instead of doing an if-statement in your code outside of your class, do this one:
Once you are logged-in, Facebook's LoginManager will be returning a Promise
The promise will then be checked. So, if you have
.then((result) => {
if(result) {
this.props.navigation.navigate('HomeScreen');
} else {
alert('...'); // Anything you want to do if login failed.
}
});
I used
FBLogout = (accessToken) => {
let logout =
new GraphRequest(
"me/permissions/",
{
accessToken: accessToken,
httpMethod: 'DELETE'
},
(error, result) => {
if (error) {
console.log('Error fetching data: ' + error.toString());
} else {
LoginManager.logOut();
}
});
new GraphRequestManager().addRequest(logout).start();
};
and added a button and used
LoginManager.logout();
<View style={styles.container}>
<SettingsView profile={this.state.profile}/>
<Button
onPress={() => {
FBLogout();
this.props.navigation.navigate('HomeScreen')
}}
title="Log Out"
color="#3b5998"
/>
</View>
I am building an app for iOS with React native and I would like to know how to take a snapshot of a given screen. I have found this library but I don't know how to use it. Does anyone know how to ?
EDIT:
I used the following code to capture a screen using the library but I get the given error.
try {
captureRef(viewRef, {
format: "jpg",
quality: 0.8
})
.then(
uri => console.log("Image saved to", uri),
error => console.error("Oops, snapshot failed", error)
);
} catch (e) {
console.log(e);
}
The error
ReferenceError: viewRef is not defined
Does anybody know how to fix the error?
Thank you
Sure, but you have to read a little about what a ref is. If you are already using React hooks, check this: https://es.reactjs.org/docs/hooks-reference.html#useref
(if not, just search on how to create a ref in React with createRef)
Basically, a ref is something that will let you identify your component using the same variable even if the component re-renders. So, viewRef in your example should be a reference to a given element. Like:
import React, { useRef } from "react";
function MyComponent() {
const viewRef = useRef();
return <View ref={viewRef}>content</View>
}
So, your draft could be something like:
import React, { useRef } from "react";
import {Button, View, Text} from 'react-native';
import { captureRef } from "react-native-view-shot";
function useCapture() {
const captureViewRef = useRef();
function onCapture() {
captureRef(captureViewRef, {
format: "jpg",
quality: 0.9
}).then(
uri => alert(uri),
error => alert("Oops, snapshot failed", error));
}
return {
captureViewRef,
onCapture
};
}
function MyComponent() {
const { captureViewRef, onCapture } = useCapture();
return (
<>
<View ref={captureViewRef}><Text>content</Text></View>
<Button title="Save" onPress={onCapture} />
</>
);
}
As far as I know, this only generates a temporary file. If you want to see the capture saved into your device, you should use CameraRoll https://facebook.github.io/react-native/docs/cameraroll
I won't cover how to use it here, but it would be something like:
CameraRoll.saveToCameraRoll(uri); // uri being the path that you get from captureRef method
Just notice that your app must ask for proper permission before attempting to save to the device gallery.
hi this can be with the help of react-native-view-shot
this is my parent component
import React, {Component,useRef} from 'react';
import {Platform, StyleSheet, Text, View,Image,Button} from 'react-native';
import { captureRef, captureScreen ,ViewShot} from "react-native-view-shot";
import NewVd from './NewVd';
import Newved from './Newved';
export default class App extends Component {
constructor(){
super();
this.state={
item:null,
captureProcessisReady:false,
myView:false
};
this.func=this.func.bind(this);
}
componentDidMount(){
}
result1=()=>{
console.log("i am here ");
this.setState({captureProcessisReady:true});
}
func = (uri) => {
console.log('ADD item quantity with id: ', uri);
this.setState({item:uri,myView:true});
};
render() {
return (
<View style={styles.container}>
{/* <NewVd
func={this.func}/> */}
<Newved />
<Text>...Something to rasterize...</Text>
<Text style={styles.welcome}>Welcome to React Native!</Text>
<Text style={styles.instructions}>To get started, edit App.js</Text>
<Button onPress={()=>this.result1()} title="press Me"/>
<View>
{this.state.captureProcessisReady?( <NewVd func={this.func}/>):null}
</View>
<View>
{this.state.myView?( <Image source={{uri:this.state.item !== null?`${this.state.item}`:'https://picsum.photos/200'}} style={{width:100,height:100}} />):null}
</View>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
instructions: {
textAlign: 'center',
color: '#333333',
marginBottom: 5,
},
});
this is my child component
import React, {Component} from 'react';
import {Platform, StyleSheet, Text, View} from 'react-native';
import ViewShot from "react-native-view-shot";
class NewVd extends Component {
constructor(props){
super(props);
}
onCapture = uri => {
console.log("do something with ", uri);
this.props.func(uri); //for the parent using callback
}
render() {
return (
<ViewShot onCapture={this.onCapture} captureMode="mount">
<Text>...Something to rasterize...</Text>
</ViewShot>
);
}
}
export default NewVd;
Need help guys, currently using exponent and accessing the Exponent.Facebook.logInWithReadPermissionsAsync for authentication. Anyone has a guide in setting up the project. I can't find the iOS folder since in the instruction of facebook sdk, I need to add few libraries on the project. Here's my main.js:
import Expo from 'expo';
import React from 'react';
import { StyleSheet, Text, View } from 'react-native';
import { Button } from 'react-native-elements';
class App extends React.Component {
authenticate = (token) => {
const provider = firebase.auth.FacebookAuthProvider;
const credential = provider.credential(token);
return firebase.auth().signInWithCredential(credential);
}
login = async () => {
const ADD_ID = 273131576444313
const options = {
permissions: ['public_profile', 'email'],
}
const {type, token} = await Expo.Facebook.logInWithReadPermissionsAsync(ADD_ID, options)
if (type === 'success') {
const response = await fetch(`https://graph.facebook.com/me?access_token=${token}`)
console.log(await response.json());
this.authenticate(token);
}
}
render() {
return (
<View style={styles.container}>
<Text>Open up main.js to start working on your app!</Text>
<Button
raised
onPress={this.login}
icon={{name: 'cached'}}
title='RAISED WITH ICON' />
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
});
Expo.registerRootComponent(App);
`
Try putting single quotes around the APP_ID