Quantcast
Channel: Active questions tagged react-native+ios - Stack Overflow
Viewing all 17130 articles
Browse latest View live

React Native linking.openUrl() not forking for facebook

$
0
0

im getting one facebook-page url from server.But im not able to launch that to facebook app installed in ios by default it opens in safari even i have facebook app installed.

i have tried like this

try {   await Linking.openURL(`fb://profile/${data_facebook_link}`);} catch {   await Linking.openURL(`https://www.facebook.com/${data_facebook_link}`);}

but nothing happen

tried this also

Linking.canOpenURL("fb://profile/XXXXXX").then(supported => {    if (supported) {      return Linking.openURL("fb://profile/XXXXXX");    } else {      return Linking.openURL("https://www.facebook.com/");    }  })

nothing works.But linking.openUrl() works for youtube link its open in youtube app if installed else open in safari.Any one came across this?


React Native - Login Page : Fit all content on screen width (resize image)

$
0
0

Hello here is a visual example of what I'm trying to accomplish:

enter image description here

This is the login screen for my app. I want to make sure that no matter what phone the user is doing everything fits on the screen without having to scroll. What I'm trying to do is make the image height dynamic so that it resizes based on the phone height.

I'm not sure how to approach this right now I have flex box set up and I have two children view inside of it. The bottom view is a fixed height so I set that equal to 220 and then for the top view I'm doing the phone height minus the fixed height.

The image and text are actually a slider that I'm using from here: https://github.com/archriss/react-native-snap-carousel

Again I'm not sure the best way to approach this, but I just want the image to resize depending on phone height. Here is my code:

const phoneHeight = Dimensions.get('window').height;const phoneWidth = Dimensions.get('window').width;_renderItem({ item, index }) {    return (<View style={{            display: 'flex',            justifyContent: 'center',            alignItems: 'center',            marginBottom: 25,            alignSelf: "center"        }}><View style={styles.ImageWrap}><Image style={styles.imageStyle} source={item.image} /></View><View style={styles.TextWrap}><Text style={styles.Title}>{item.title}</Text><Text style={styles.Body}>{item.text}</Text></View></View>    )}    render() {        return (<><SafeAreaView style={styles.app}><View style={styles.appBody}><View style={styles.headerWrap}>                            {/* HEADER CONTENT HERE */}</View><Carousel                            layout={"default"}                            ref={ref => this.carousel = ref}                            data={this.state.carouselItems}                            sliderWidth={phoneWidth - 50}                            itemWidth={phoneWidth - 50}                            renderItem={this._renderItem}                            onSnapToItem={index => this.setState({ activeIndex: index })} /><View>                            {/* Some Text Here HERE */}</View></View><View style={styles.footerWrap}>                        {/* FIXED CONTENT HERE */}</View></SafeAreaView></>        );    }}const styles = StyleSheet.create({    loginBody: {        display: 'flex',        height: '100%',        flexDirection: 'column',        justifyContent: 'center',    },    appBody: {        height: phoneHeight - 220,    },    footerWrap: {        height: 220,    },    ImageWrap: {        height: phoneHeight / 4,            },    imageStyle: {        height: '100%',        width: 'auto',    },});

How to disable font scaling in React Native for IOS app?

$
0
0

Enlargement of size of the device font will sometimes break (Styling wise).

Show an UIViewController into a React Native app

$
0
0

I'm triying to integrate a swift library that has his own UIViewController, I had already made the bridge between react and swift but I only can show a UIView, any idea how to show it?

Guys I need your help about react-native

$
0
0

Hi dear stackoverflow members. We will create Android & IOS Hybrid app and we want to use React Native for that. Our app will have kind of 12 page and it will be simular Tinder something like that. We will use location api and cloud services for database. We wondering about React Native performances. Is anyone work with simular projects with React and how was the results. Thx a lot for everyone.

Why Keychain reset data on app kill in IOS(react native)? Is there any reason?

$
0
0

Currently, when I kill the App on the first-time keychain persist data perfectly. However, on the second time, on App killing keychain reset credentials. Here is my code:

  componentDidMount() {        AppState.addEventListener('change', this._handleAppStateChange);        Keychain.getGenericPassword()        .then((credentials) => {          console.log(credentials.username,'Credentials Log')            if (credentials.username === '' ||  credentials.username === undefined) {                  this.setState({isKeyClear:true,isTouchShow:false})            } else {                  this.setState({isKeyClear:false,isTouchShow:true});                  // this.clickTouchID();            }        })        .catch(err => {            console.log("err: ", err);        });  }

Here, i checked the Touch Id or face Id support:

  clickTouchID  = () => {    console.log('Click');    TouchID.isSupported()      .then(biometryType => {        if(biometryType){          if (biometryType === 'TouchID') {            // Touch ID is supported on iOS            // this.setCredentials(username, password);            this.getCredentials();          } else if (biometryType === 'FaceID') {            // Face ID is supported on iOS            this.getCredentials();          } else if (biometryType === true) {            console.log(biometryType,'Android');            // Touch ID is supported on Android            this.getCredentials();          }        }        else{            console.log('Not Supported');        }    })    .catch(error => {      console.log('Users device does not support Touch ID (or Face ID)', error);      this.devicesSupportedAlert();      // User's device does not support Touch ID (or Face ID)      // This case is also triggered if users have not enabled Touch ID on their device    });  }

This method store credentials in keychain:

  setCredentials = async (username, password) => {    return new Promise((resolve, reject) => {        // Store the credentials        Keychain.setGenericPassword(username, password, {accessible: Keychain.ACCESSIBLE.ALWAYS})            .then(resp => {                console.log(resp,'Setcredentials Response');                // this.getCredentials();                resolve(true)            })            .catch(err => {                console.log("err: Detail", err);                reject(err);            });    });  }

This method gets credentials in keychain but conditions first check if data exist or not.

  getCredentials = async () => {    return new Promise((resolve, reject) => {        Keychain.getGenericPassword()            .then((credentials) => {                if (credentials.username === '' ||  credentials.username === undefined) {                    if(isAndroid){                      this.setState({isKeyClear:true,isTouchShow:false})                    }                      console.log('No credentials stored');                      resolve(credentials);                } else {                      if(isAndroid){                        this.setState({isKeyClear:false,isTouchShow:true})                      }                      console.log('Credentials successfully loaded for user'+ credentials.username);                        // If Touch ID authentication is successful, call the `login` api                  TouchID.authenticate()                     .then(() => {                    // If Touch ID authentication is successful, call the `login` api                    this.setState({bioState:true});                    let userObj = {                      Isemail:credentials.username,                      Ispassword:credentials.password                    }                    this.onPressLogin(userObj)                  })                  .catch(error => {                    console.log("error: ", error);                    reject(error);                  })                }            })            .catch(err => {                console.log("err: ", err);                reject(err);            });    });  }  _handleAppStateChange = (nextAppState) => {    if(isAndroid){      if (nextAppState === 'background' ||  nextAppState === 'active') {          this.clickTouchID();          console.log('the app is closed Android');      }    }    else if(nextAppState === 'inactive') {        console.log('the app is closed IOS');    }  }

How can i add this in my react native project? [closed]

$
0
0

Project Image

As you can see in the image I have selected the item i want to create i don't know what it's called can any one help please?

React Native Expo: Placing a Camera inside a ViewPager

$
0
0

I need to put a Camera ("expo-camera") view inside a horizontal viewPager ("@react-native-community/viewpager").I can't get it to work.

I was able to place other components with no problem, and I was able to show the Camera as a stand alone view.I'm still a beginner.Is this possible?If so, can someone make a simple template of these two components together please?

ViewPager:

import React from "react";import ViewPager from "@react-native-community/viewpager";import Record from "../../components/Record";import { View } from "react-native";const Home: React.FC = () => {  return (<ViewPager      onPageSelected={(event) => {        //Nothing yet      }}      style={{ flex: 1, backgroundColor: "#000" }}      orientation="horizontal"      scrollEnabled={true}><View style={{ flex: 1, backgroundColor: "#f54242" }} /><Record isFeed={false} /></ViewPager>  );};export default Home;

Camera:

import React, { useEffect } from "react";import { Camera } from "expo-camera";import { View, Text, StatusBar } from "react-native";const Record: React.FC = () => {  const [hasPermission, setHasPermission] = useState<boolean | null>(null);  useEffect(() => {    async function permission(): Promise<void> {      const { status } = await Camera.requestPermissionsAsync();      setHasPermission(status === "granted");      StatusBar.setHidden(true);    }    permission();  }, []);  if (hasPermission === null) {    return <View />;  }  if (hasPermission === false) {    return <Text>No access to camera</Text>;  }  return (<Camera type={Camera.Constants.Type.back}/>  );};export default Record;

Appreciate all the help I can get.


How can I fix the error shown below in react-native?

$
0
0

console.error: The action 'Navigation/OPEN_DRAWER' was not handled by any navigator.

This is a development-only warning and won't be shown in production.

My code is shown below.

MainTabScreen.js

import * as React from 'react';import { createMaterialBottomTabNavigator } from '@react-navigation/material-bottom-tabs';import { createStackNavigator } from '@react-navigation/stack';import Icon from 'react-native-vector-icons/Ionicons';import DashboardScreen from './DashboardScreen';import OpportunitiesScreen from './OpportunitiesScreen';import ProfileScreen from './EditProfileScreen';import { DrawerActions } from 'react-navigation-drawer';const DashboardStack = createStackNavigator();const OpportunitiesStack = createStackNavigator();const ProfileStack = createStackNavigator();const Tab = createMaterialBottomTabNavigator();const DashboardStackScreen = (props) => (<DashboardStack.Navigator screenOptions={{          headerStyle: {          backgroundColor: '#7b68ee',          },          headerTintColor: '#fff',          headerTitleStyle: {          fontWeight: 'bold'          }      }}><DashboardStack.Screen name="Dashboard" component={DashboardScreen} options={{          title:'Dashboard',          headerLeft: () => (<Icon.Button name="ios-menu" size={25} backgroundColor="#7b68ee" onPress={() => props.navigation.dispatch(DrawerActions.openDrawer())}></Icon.Button>          )          }} /></DashboardStack.Navigator>  );  const OpportunitiesStackScreen = (props) => (<OpportunitiesStack.Navigator screenOptions={{          headerStyle: {          backgroundColor: '#7b68ee',          },          headerTintColor: '#fff',          headerTitleStyle: {          fontWeight: 'bold'          }      }}><OpportunitiesStack.Screen name="Opportunities" component={OpportunitiesScreen} options={{          headerLeft: () => (<Icon.Button name="ios-menu" size={25} backgroundColor="#7b68ee" onPress={() => props.navigation.dispatch(DrawerActions.openDrawer())}></Icon.Button>          )          }} /></OpportunitiesStack.Navigator>  );  const ProfileStackScreen = (props) => (<ProfileStack.Navigator screenOptions={{            headerStyle: {            backgroundColor: '#7b68ee',            },            headerTintColor: '#fff',            headerTitleStyle: {            fontWeight: 'bold'            }        }}><ProfileStack.Screen name="Profile" component={ProfileScreen} options={{            headerLeft: () => (<Icon.Button name="ios-menu" size={25} backgroundColor="#7b68ee" onPress={() => props.navigation.dispatch(DrawerActions.openDrawer())}></Icon.Button>          )            }} /></ProfileStack.Navigator>    );const MainTabScreen = () => (<Tab.Navigator      initialRouteName="Dashboard"      activeColor="#fff"><Tab.Screen        name="Dashboard"        component={DashboardStackScreen}        options={{          tabBarLabel: 'Dashboard',          tabBarColor: '#009387',          tabBarIcon: ({ color }) => (<Icon name="ios-home" color={color} size={26} />          ),        }}      /><Tab.Screen        name="Opportunities"        component={OpportunitiesStackScreen}        options={{          tabBarLabel: 'Opportunities',          tabBarColor: '#1f65ff',          tabBarIcon: ({ color }) => (<Icon name="ios-aperture" color={color} size={26} />          ),        }}      /><Tab.Screen        name="Profile"        component={ProfileStackScreen}        options={{          tabBarLabel: 'Profile',          tabBarColor: '#694fad',          tabBarIcon: ({ color }) => (<Icon name="ios-person" color={color} size={26} />          ),        }}      /></Tab.Navigator>);export default MainTabScreen;

App.js

import React, { useEffect } from 'react';import { View, ActivityIndicator } from 'react-native';import {   NavigationContainer,   DefaultTheme as NavigationDefaultTheme,  DarkTheme as NavigationDarkTheme} from '@react-navigation/native';import { createDrawerNavigator } from '@react-navigation/drawer';import {   Provider as PaperProvider,   DefaultTheme as PaperDefaultTheme,  DarkTheme as PaperDarkTheme } from 'react-native-paper';import { DrawerContent } from './screens/DrawerContent';import MainTabScreen from './screens/MainTabScreen';import SupportScreen from './screens/SupportScreen';import SettingsScreen from './screens/SettingsScreen';import BookmarkScreen from './screens/BookmarkScreen';import { AuthContext } from './components/context';import RootStackScreen from './screens/RootStackScreen';import AsyncStorage from '@react-native-community/async-storage';const Drawer = createDrawerNavigator();const App = () => {  // const [isLoading, setIsLoading] = React.useState(true);  // const [userToken, setUserToken] = React.useState(null);   const [isDarkTheme, setIsDarkTheme] = React.useState(false);  const initialLoginState = {    isLoading: true,    userName: null,    userToken: null,  };  const CustomDefaultTheme = {    ...NavigationDefaultTheme,    ...PaperDefaultTheme,    colors: {      ...NavigationDefaultTheme.colors,      ...PaperDefaultTheme.colors,      background: '#ffffff',      text: '#333333'    }  }  const CustomDarkTheme = {    ...NavigationDarkTheme,    ...PaperDarkTheme,    colors: {      ...NavigationDarkTheme.colors,      ...PaperDarkTheme.colors,      background: '#333333',      text: '#ffffff'    }  }  const theme = isDarkTheme ? CustomDarkTheme : CustomDefaultTheme;  const loginReducer = (prevState, action) => {    switch( action.type ) {      case 'RETRIEVE_TOKEN':         return {          ...prevState,          userToken: action.token,          isLoading: false,        };      case 'LOGIN':         return {          ...prevState,          userName: action.id,          userToken: action.token,          isLoading: false,        };      case 'LOGOUT':         return {          ...prevState,          userName: null,          userToken: null,          isLoading: false,        };      case 'REGISTER':         return {          ...prevState,          userName: action.id,          userToken: action.token,          isLoading: false,        };    }  };  const [loginState, dispatch] = React.useReducer(loginReducer, initialLoginState);  const authContext = React.useMemo(() => ({    signIn: async(foundUser) => {      // setUserToken('fgkj');      // setIsLoading(false);      const userToken = String(foundUser[0].userToken);      const userName = foundUser[0].username;      try {        await AsyncStorage.setItem('userToken', userToken);      } catch(e) {        console.log(e);      }      // console.log('user token: ', userToken);      dispatch({ type: 'LOGIN', id: userName, token: userToken });    },    signOut: async() => {      // setUserToken(null);      // setIsLoading(false);      try {        await AsyncStorage.removeItem('userToken');      } catch(e) {        console.log(e);      }      dispatch({ type: 'LOGOUT' });    },    signUp: () => {      // setUserToken('fgkj');      // setIsLoading(false);    },    toggleTheme: () => {      setIsDarkTheme( isDarkTheme => !isDarkTheme );    }  }), []);  useEffect(() => {    setTimeout(async() => {      // setIsLoading(false);      let userToken;      userToken = null;      try {        userToken = await AsyncStorage.getItem('userToken');      } catch(e) {        console.log(e);      }      // console.log('user token: ', userToken);      dispatch({ type: 'RETRIEVE_TOKEN', token: userToken });    }, 1000);  }, []);  if( loginState.isLoading ) {    return(<View style={{flex:1,justifyContent:'center',alignItems:'center'}}><ActivityIndicator size="large"/></View>    );  }  return (<PaperProvider theme={theme}><AuthContext.Provider value={authContext}><NavigationContainer theme={theme}>      { loginState.userToken !== null ? (<Drawer.Navigator drawerContent={props => <DrawerContent {...props} />}><Drawer.Screen name="HomeDrawer" component={MainTabScreen} /><Drawer.Screen name="SupportScreen" component={SupportScreen} /></Drawer.Navigator>      )    :<RootStackScreen/>    }</NavigationContainer></AuthContext.Provider></PaperProvider>  );}

export default App;

How can I fix this error so that my drawer opens?

I am using React Native with Expo.

..........................................................................

How can i get user mobile usage details in IOS? user spend how much time in on which app?

$
0
0

How can i use IOS App Screen Time API? is IOS offer this ?

I want to get access to the user mobile usage details that how much time user spend on which app. Is there any way i can achieve in IOS with SWIFT or React Native ?

How to smudge part of a view in React Native?

$
0
0

I would like to blur part of an Image wherever user drags his finger, I don't want to blur the whole image. Here is my hacky way of doing blur

I am using @react-native-community/blur for blurring the view

const MyView = () => {  const [locations, setLocation] = useState([]);  const [top, setTop] = useState();  const [left, setLeft] = useState();  return (<><View        style={styles.container}        onTouchEnd={(event) => {          console.log(event.nativeEvent.locationX);          console.log(event.nativeEvent.locationY);          setLocation([            ...locations,            {              right: event.nativeEvent.locationX,              bottom: event.nativeEvent.locationY,              top,              left,            },          ]);        }}        onTouchStart={(event) => {          console.log('S'+ event.nativeEvent.locationX);          console.log('S'+ event.nativeEvent.locationY);          setLeft(event.nativeEvent.locationX);          setTop(event.nativeEvent.locationY);        }}><ImageBackground          style={{width, height}}          source={{            uri:'https://images.unsplash.com/photo-1593642634315-48f5414c3ad9?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1050&q=80',          }}><Text>Hi there </Text></ImageBackground></View>      {locations.map((l, index) => {        return (<BlurView            key={index.toString()}            style={{              width: l.right - l.left,              height: l.bottom - l.top,              backgroundColor: 'rgba(0,0,0,0.1)',              position: 'absolute',              top: parseFloat(l.top),              left: parseFloat(l.left),              right: parseFloat(l.right),              bottom: parseFloat(l.bottom),              // blurR,              // opacity: 0.4,            }}            blurType="light"            blurAmount={4}            reducedTransparencyFallbackColor="white"          />        );      })}</>);};

This is a really hacky way of smudging part of an image where user drags his finger. On Android , the application just stops responding as soon as I move my finger on more than two places. Does anyone know a better way to smudge part of view instead of blurring the whole image view where user drags his finger

React Native CLI uses autolinking for native dependencies, but the following modules are linked manually:

$
0
0

I am new to react-native ios development. I am getting an error at run time.

error React Native CLI uses autolinking for native dependencies, but the following modules are linked manually:

  • react-native-image-picker (to unlink run: "react-native unlink react-native-image-picker")
  • react-native-vector-icons (to unlink run: "react-native unlink react-native-vector-icons")This is likely happening when upgrading React Native from below 0.60 to 0.60 or above. Going forward, you can unlink this dependency via "react-native unlink " and it will be included in your app automatically. If a library isn't compatible with autolinking, disregard this message and notify the library maintainers.Read more about autolinking: https://github.com/react-native-community/cli/blob/master/docs/autolinking.mdinfo Found Xcode workspace "Usam.xcworkspace"info Building (using "xcodebuild -workspace Usam.xcworkspace -configuration Debug -scheme Usam -destination id=864564F6-8E02-4C19-BFBD-9A798FFD31B2").............................................................................error Failed to build iOS project. We ran "xcodebuild" command but it exited with error code 65. To debug build logs further, consider building your app with Xcode.app, by opening Usam.xcworkspace. Run CLI with --verbose flag for more details.note: Using new build systemnote: Planning build

React Native App Crash (Thread 1: EXC_BAD_ACCESS (code=1, address=0x54))

$
0
0

Recently came onto this issue when trying to run my app on the simulator through xCode or the React Native CLI. The bundle loads from localhost then the app immediately crashes with "Thread 1: EXC_BAD_ACCESS (code=1, address=0x54)" in "main.m" in Xcode. I am unable to get the app running even though it builds fine. (even tried running on release instead of debug)

error in main.m

This issue just started recently occurring and I cannot find anything in our Git logs that would cause any kind of issue - all pretty minor changes on the RN side and nothing native. Has anyone seen this issue/knows how to properly trace it? Seems like a super generic error and it is unclear on how to figure out what is actually going on.

Xcode version 11.5, React Native 0.62.0, and targetting iOS 10.

EDIT:After running the app a few times I was able to get this error in the Xcode Output

Xcode output

react-native run-ios is not working

$
0
0

I have a react native ios and it was working fine, suddnly it's working only in Xcode but not in terminal using this command:

react-native run-iosreact-native run-ios --device

Both of command are not working in the root directory, I tried to delete node_modules folder then run:

npm install; react-native link;

Unfortunatly it's not working, here are my logs:

enter image description hereenter image description hereenter image description here

Any Help!

Library not found for -lDoubleConversion Build failed

$
0
0

enter image description here

ALREADY TRY THIS

https://stackoverflow.com/questions/50562596/library-not-found-for-ldoubleconversion

https://stackoverflow.com/questions/55239646/ld-library-not-found-for-ldoubleconversion-react-native-0-59

here is what i did

  • I clean and rebuild
  • rm -f ~/Library/Developer/Xcode/DerivedData/cache
  • also add remove flags from Other Linker Flags
  • also try to add .a file in Link Binary With library under build phase

Still Not get Success


How to integrate OpenStreetMap into a react-native project?

$
0
0

I am trying to integrate OpenStreetMap into a React Native project. But I can't find any library or anything related to React Native in their GitHub account.

The only thing I can find relating to these to topics is the link below, in which there is no proper answer.

https://www.reddit.com/r/reactnative/comments/5fi6bg/how_to_add_openstreetmap_to_a_react_native_project/

But I heard once that Mapbox uses OpenStreetMap as their source. Mapbox suggests a good way to integrate it into a React Native project:

https://github.com/mapbox/react-native-mapbox-gl

Is there a way to integrate OpenStreetMap into a React Native projector is it the case there's not proper support for it yet.

ld: library not found for -lDoubleConversion React Native 0.59

$
0
0

I have this error

❌  ld: library not found for -lDoubleConversion❌  clang: error: linker command failed with exit code 1 (use -v to see invocation)error Failed to build iOS project. We ran "xcodebuild" command but it exited with error code 65. To debug build logs further, consider building your app with Xcode.app, by opening App.xcworkspace** BUILD FAILED **The following build commands failed:    Ld /Users/mohamedelmi/workspace/elmi/food-frontend/ios/build/App/Build/Intermediates.noindex/App.build/Release-iphonesimulator/App.build/Objects-normal/x86_64/App normal x86_64(1 failure)

here is what i did

  1. I clean and rebuild still have the error
  2. rm -f ~/Library/Developer/Xcode/DerivedData/ModuleCach

React-native-maps and Geolocation not getting location properly

$
0
0

I am very new to learning React Native and would appreciate any help that can be provided with my code. I am currently working off of tutorials and have been stuck for hours. Hopefully this is enough info to get some help. Thanks in advance!

My goal

I am trying to do three things (in this order):

  1. Get the user's current location
  2. Fetch the items data from an API (example outlined below). It should be noted that eventually the contents of the fetch will be dependent on the user's current location.
  3. Parse the items data to create markers and a unique list of categories and place those on the map with the user's current location at center to begin with.

I am looking to be able to watch the user's location and move and update the map accordingly. I also don't want to show the map until all of the markers are in place.

Here are my react versions: react-native-cli: 2.0.1 react-native: 0.63.2

My Bugs

I am using both the Android Studio emulator as well as the Xcode emulator and am currently running into the following problems:

  1. The iOS emulator on Xcode renders fine the first time, but on subsequent refreshes I see 1 or two of my 5 markers missing.
  2. On Android, the map loads perfectly then appears to immediately redraw itself and center on the Googleplex in California instead of the user's current location.Emulator location is set to London, UK

I suspect I might have some race condition with fetching the items and current location before the map renders but I can't be sure.

My Code

//my API response structure

{"id": "96845","title": "Item_title_goes_here","image": "https://someURL/image.JPG","stories": 46,"lat": some_lat_number,"lon": some_lon_number,"category": "category_name","description": "long_description"},
//ajax.js export default {    async fetchInitialItems() {        try {            const response = await fetch(apiHost +'/api/v1/items/');            const responseJson = await response.json();            return responseJson;        } catch (error) {            console.error(error);        }    },    async fetchItemDetail(itemId) {        try {            const response = await fetch(apiHost +'/api/items/'+ itemId);            const responseJson = await response.json();            return responseJson;        } catch (error) {            console.error(error);        }    },};
//ExploreScreen.js (my map component)import React, { Component } from 'react';import {    View,    Text,    StyleSheet,    Image,    Animated,    Dimensions,    TouchableOpacity,    PermissionsAndroid,    ScrollView,    Platform,    StatusBar,} from 'react-native';import MapView, {    PROVIDER_GOOGLE,    Marker,    Callout,    Polygon,} from 'react-native-maps';import PropTypes from 'prop-types';import Geolocation from '@react-native-community/geolocation';import { mapDarkStyle, mapStandardStyle } from '../model/mapData';import ajax from '../utils/ajax';import MapCarousel from './MapCarousel';import Ionicons from 'react-native-vector-icons/Ionicons';import MaterialCommunityIcons from 'react-native-vector-icons/MaterialCommunityIcons';import Fontisto from 'react-native-vector-icons/Fontisto';import StarRating from '../components/StarRating';/**|--------------------------------------------------| Variables|--------------------------------------------------*/const { width, height } = Dimensions.get('window');const SCREEN_HEIGHT = height;const SCREEN_WIDTH = width;const ASPECT_RATIO = width / height;const LATITUDE_DELTA = 0.0422;const LONGITUDE_DELTA = LATITUDE_DELTA * ASPECT_RATIO;const darkTheme = false;/**|--------------------------------------------------| Component|--------------------------------------------------*/class ExploreScreen extends React.Component {    /****** Props & States ******/    state = {        region: {            latitude: 0,            longitude: 0,            latitudeDelta: LATITUDE_DELTA,            longitudeDelta: LONGITUDE_DELTA,        },        items: [],        markers: [],        categories: [],        currentMapRegion: null,    };    /****** Functions ******/    ///when carousel item selected    onCarouselItemSelected() {        alert('carousel item selected');    }    //when the carousel in scrolled    onCarouselIndexChange(itemID) {        const item = this.state.items.find(item => item.id == itemID);        const marker = this.state.markers.find(marker => marker.id == itemID);        const coordinates = { lat: item.lat, lon: item.lon };        this.goToLocation(coordinates);    }    //get current position    getLocation(that) {        Geolocation.getCurrentPosition(            //get the current location            position => {                const region = {                    latitude: parseFloat(position.coords.latitude),                    longitude: parseFloat(position.coords.longitude),                    latitudeDelta: LATITUDE_DELTA,                    longitudeDelta: LONGITUDE_DELTA,                };                that.setState({ region });            },            error => alert(error.message),            { enableHighAccuracy: true, timeout: 20000 },        );        //get location on location change        that.watchID = Geolocation.watchPosition(position => {            const currentRegion = {                latitude: position.coords.latitude,                longitude: position.coords.longitude,                latitudeDelta: LATITUDE_DELTA,                longitudeDelta: LONGITUDE_DELTA,            };            this.setState({ region: currentRegion });        });    }    //move map to a lat/lon    goToLocation(coordinates) {        if (this.map) {            this.map.animateToRegion({                latitude: coordinates.lat,                longitude: coordinates.lon,                latitudeDelta: LATITUDE_DELTA,                longitudeDelta: LONGITUDE_DELTA,            });        }    }    //when the region changes for the map    onRegionChangeComplete(region) {        //I dont know what to do here     }    //move map to center of current location    gotToCenter() {        if (this.map) {            this.map.animateToRegion({                latitude: this.state.region.latitude,                longitude: this.state.region.longitude,                latitudeDelta: LATITUDE_DELTA,                longitudeDelta: LONGITUDE_DELTA,            });        }    }    //map the categories store in the state    mapCategories = () => {        const uniqueCategories = [];        this.state.items.map(item => {            if (uniqueCategories.indexOf(item.category) === -1) {                uniqueCategories.push(item.category);            }        });        this.setState({ categories: uniqueCategories });    };    //map the items to markers and store in the state    mapMarkers = () => {        const markers = this.state.items.map(item => (<Marker                key={item.id}                coordinate={{ latitude: item.lat, longitude: item.lon }}                image={require('../assets/map_marker.png')}                tracksViewChanges={false}                title={item.title}                description={item.description}            />        ));        this.setState({ markers: markers });    };    /****** Lifecycle Functions ******/    async componentDidMount() {        var that = this;        //Checking for the permission just after component loaded        if (Platform.OS === 'ios') {            //for ios            this.getLocation(that);        } else {            //for android            async function requestLocationPermission() {                try {                    const granted = await PermissionsAndroid.request(                        PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,                        {                            title: 'Location Access Required',                            message: 'This App needs to Access your location',                        },                    );                    if (granted === PermissionsAndroid.RESULTS.GRANTED) {                        //To Check, If Permission is granted                        that.getLocation(that);                    } else {                        alert('Permission Denied');                    }                } catch (err) {                    alert('err', err);                    console.warn(err);                }            }            requestLocationPermission();        }        //get location on location change        that.watchID = Geolocation.watchPosition(position => {            const currentRegion = {                latitude: parseFloat(position.coords.latitude),                longitude: parseFloat(position.coords.longitude),                latitudeDelta: LATITUDE_DELTA,                longitudeDelta: LONGITUDE_DELTA,            };            this.setState({ region: currentRegion });        });        console.log(this.state.region);        const items = await ajax.fetchInitialItems();        this.setState({ items });        this.mapMarkers();        this.mapCategories();    }    componentWillUnmount = () => {        Geolocation.clearWatch(this.watchID);    };    render() {        const lat = this.state.region.latitude;        const lon = this.state.region.longitude;        if (this.state.items && lat && lon) {            return (<View><MapView                        ref={map => {                            this.map = map;                        }}                        onRegionChangeComplete={this.onRegionChangeComplete.bind(this)}                        toolbarEnabled={false}                        showsMyLocationButton={false}                        provider={PROVIDER_GOOGLE}                        style={styles.map}                        customMapStyle={darkTheme ? mapDarkStyle : mapStandardStyle}                        showsUserLocation={true}                        followsUserLocation={true}                        region={this.state.region}>                        {this.state.markers}</MapView>                    {/* center button */}<TouchableOpacity                        onPress={this.gotToCenter.bind(this)}                        style={styles.centerButtonContainer}><Ionicons name="md-locate" size={20} /></TouchableOpacity><View style={styles.carousel}><MapCarousel                            data={this.state.items}                            onPressItem={() => {                                this.onCarouselItemSelected.bind(this);                            }}                            onUpdateLocation={this.onCarouselIndexChange.bind(this)}                        /></View></View>            );        } else {            return (<View style={styles.container}><Text style={styles.header}>Loading...</Text></View>            );        }    }}/**|--------------------------------------------------| Styles|--------------------------------------------------*/const styles = StyleSheet.create({    container: {        ...StyleSheet.absoluteFillObject,        height: '100%',        width: '100%',        justifyContent: 'center',        alignItems: 'center',    },    map: {        height: '100%',    },    carousel: {        position: 'absolute',        bottom: 25,    },    header: {        fontSize: 50,    },    //character name    name: {        fontSize: 15,        marginBottom: 5,    },    //character image    image: {        width: 170,        height: 80,    },    //center button    centerButtonContainer: {        width: 40,        height: 40,        position: 'absolute',        bottom: 260,        right: 10,        borderColor: '#191919',        borderWidth: 0,        borderRadius: 30,        backgroundColor: '#d2d2d2',        justifyContent: 'center',        alignItems: 'center',        shadowColor: '#000',        shadowOffset: {            width: 0,            height: 9,        },        shadowOpacity: 0.48,        shadowRadius: 11.95,        elevation: 18,        opacity: 0.9,    },});export default ExploreScreen;

Firebase React Native Dynamic Links - Always retun null in Android phone and Ios [closed]

$
0
0

"@react-native-firebase/app": "^8.2.0","@react-native-firebase/dynamic-links": "^7.3.2","react-native": "0.59.10",

Is there a specific component in React Native for implementing this kind of interaction?

$
0
0

there is one app named TimeBuddy in Android and iOS which displays time strip of selected locations and the user can drag one indicator to compare different time zones in that app. I want to know whether there is something like that in React Native?

Here is the screenshot of that app.

Thanks in Advance.

Viewing all 17130 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>