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

Wrong Geolocation with React Native and iOS simulator

$
0
0

I am working with react-native-maps and using the react-native api for geolocation. When I am using location through the api what comes back on the simulator shows me in San Francisco not in Denver, CO where I am located. Is there a reason as to why my location would not show where I am at?

my function that runs the location

  // Get current users locaiton on load  componentDidMount() {    navigator.geolocation.getCurrentPosition((position) => {      console.log(position);      let newLat = parseFloat(position.coords.latitude);      console.log("newLat", newLat);      let newLng = parseFloat(position.coords.longitude);      console.log("newLng", newLng);      // set region of user to lat and long position      // deltas set distance from marker (zoom) on map      this.setState({        region: {          latitude: newLat,          longitude: newLng,          latitudeDelta: 0.0250,          longitudeDelta: 0.0125        },        error: null      });      console.log(this.state);    },       // if error set state with error      (err) => {        console.log(err),        // set location accuracy on        // max time to find location in 5 sec        // max time to use cached location for phone 5 sec        { timeout: 5000, maximumAge: 5000 };      }    );    // watch for changes and update location    this.watchId = navigator.geolocation.watchPosition((position) => {      console.log(position);      let newLat = parseFloat(position.coords.latitude);      console.log("newLat", newLat);      let newLng = parseFloat(position.coords.longitude);      console.log("newLng", newLng);      // set region of user to lat and long position      // deltas set distance from marker (zoom) on map      this.setState({        region: {          latitude: newLat,          longitude: newLng,          latitudeDelta: 0.0250,          longitudeDelta: 0.0125        },        error: null      });      console.log(this.state);    },      (err) => {        console.log(err),        // set location accuracy on        // max time to find location in 5 sec        // max time to use cached location for phone 5 sec        // distance before location called again 10 m        { timeout: 5000, maximumAge: 5000, distanceFilter: 10 }      }    );  }

my location preset in initial state is :

this.state ={      region: {          latitude: 39.739236,          longitude: -104.990251,          latitudeDelta: 0.1000,          longitudeDelta: 0.0500      },

which is relatively closer than where the iOS simulator shows me atconsole log of my location

anyone run into this problem and know how to solve it? Is it the network that react-native is running on or shouldn't it be pulling from my laptops network location?

I have looked to see if anyone else ran into this issue:Geolocation in React Native iOSand the search on stack only shows 6 results if you search for geolocation wrong react-native ios...google wasn't much help either.

Thanks for your help


React Native: wake a locked phone and play a sound

$
0
0

I am building a running app that shows a timer. When the timer reaches 0 seconds a sound is played. I use React Native Sound for playback. I use an interval on componentDidMount for counting the seconds:

componentDidMount() {    this.recalcTotalSeconds();    KeepAwake.activate();    this._interval = setInterval(() => {        this.step();    }, 999);}

It works nicely as long as the phone is unlocked. When the phone is locked the interval is not fired and the sound is not played. As a first measure I uploaded a version with Keep Awake that prevents the screen from locking. I am looking for a battery-friendly solution.

timer screen

How can I set a timeout to wake the phone up or at least play a sound to alert the user to unlock the phone? How can I play sound in the background when the phone is locked?

Is it possible to keep the socket.io open even when the app is closed

$
0
0

I am learning the ways to build a Chat app for iOS and Android using React Native and Socket.io. At the point, the socket is always connected to the server when the app is on foreground. The problem here now is when the app is manually closed by the user, the socket disconnects and never comes alive until the User switches it back.

After a research on it I came out with Headless js which acts as a service but unfortunately it only works on Android and not iOS.

Is there any idea as to how to work this around to make the socket open even when the user closes the app? I would be grateful to know.

Notification not receiving in iOS for react native project

$
0
0

I have a react native project. I am able to receive the FCM token successfully but when trying to send a notification, the app doesn't receive the notification.
The steps I followed are as below:

  1. Created a project in Firebase Console.
  2. Added the Firebase .plist in the projectName through Xcode.
  3. ran npm install --save react-native-firebase
  4. Added in podfile: pod ‘Firebase/Core’
  5. ran pod install
  6. Update AppDelegate.m with #import <Firebase.h> and [FIRApp configure];
  7. Added the APNS in the Firebase Dashboard for iOS App Cloud Messaging.
  8. Updated the capabilities with Push Notification and Background Modes > Remote notification
  9. In info.plist FIRAnalyticsDebugEnabled, FirebaseAppDelegateProxyEnabled, FirebaseScreenReportingEnabled is set to No

using const fcmToken = await firebase.messaging().getToken(); I am able to get token.

Below is the code for the notification listener.

async createNotificationListeners() {    /*     * Triggered when a particular notification has been received in foreground     * */    this.notificationListener = firebase.notifications().onNotification((notification) => {        const {            title,            body        } = notification;        this.custom_data = notification.data;        const localNotification = new firebase.notifications.Notification({                show_in_foreground: true,            })            .setSound('default')            .setNotificationId(notification.notificationId)            .setTitle(notification.title)            .setBody(notification.body)        firebase.notifications()            .displayNotification(localNotification)            .catch(err => Alert.alert(err));    });    /*     * If your app is in foreground and background, you can listen for when a notification is clicked / tapped / opened as follows:     * */    this.notificationOpenedListener = firebase.notifications().onNotificationOpened((notificationOpen) => {        if ("title" in notificationOpen.notification.data) {            const {                title,                body,                secret_key,                user_id,                realm_id,                user_os,                user_location            } = notificationOpen.notification.data;            this.props.navigation.navigate('Verify', {                title: title,                body: body,                secret_key: secret_key,                user_id: user_id,                realm_id: realm_id,                user_os: user_os,                user_location: user_location            });        } else {            const {                title,                body,                secret_key,                user_id,                realm_id,                user_os,                user_location            } = this.custom_data;            this.props.navigation.navigate('Verify', {                title: title,                body: body,                secret_key: secret_key,                user_id: user_id,                realm_id: realm_id,                user_os: user_os,                user_location: user_location            });        }    });    /*     * If your app is closed, you can check if it was opened by a notification being clicked / tapped / opened as follows:     * */    const notificationOpen = await firebase.notifications().getInitialNotification();    if (notificationOpen) {        const {            title,            body,            secret_key,            user_id,            realm_id,            user_os,            user_location        } = notificationOpen.notification.data;        this.props.navigation.navigate('FCM', {            title: title,            body: body,            secret_key: secret_key,            user_id: user_id,            realm_id: realm_id,            user_os: user_os,            user_location: user_location        });    }    /*     * Triggered for data only payload in foreground     * */    this.messageListener = firebase.messaging().onMessage((message) => {        console.log("JSON.stringify:", JSON.stringify(message));    });}

Please do let me know if more details required.

Is their an equivalent of react natives "Hot Reloading" for native iOS Simulator development?

$
0
0

I'm wondering if there is a way to see UI changes in an iOS application without having to restart the device or simulator. I know in react native since they use Javascript you're able to make a change to the background colour of a view and the background would reflect that change without having to restart the simulator. So I'm thinking since react native just converts javascript into native app code this might be possible in Native Development? Yes no maybe?

React-Native-iap getProducts() returns empty array

$
0
0

Version of react-native-iap3.3.7

Version of react-native0.60.4

Platforms you faced the error (IOS or Android or both?)only on ios

Expected behaviorgetProducts returns array of products

Actual behaviorreturns empty arrayit is working well on android

Tested environment (Emulator? Real Device?)Emulator and Real Device

AdditionAll in app purchase products were already approved in app store.I also tried to use version 4.4.8, but no difference. :(Please help me.

react native app works on debug mode, but not works release mode on ios

$
0
0

I Have an app on react native. Debug mode works on ios. But Release mode not works. I tried change the optimization level but not helped. The problem that I don't see any error. Just not working some functional. And I can't debug release version of app. How to solve this problem?

As a last change we added following saga, when we remove calling this saga it works

import { select, take, takeLatest, call, put, fork, race } from 'redux-saga/effects';import R from 'ramda';import V from 'o-validator';import * as actionCreators from './actions';import { redirectTo, showModalError, showModal, showOtp, closeOtp, errorOtp, loader, keychainSet } from '../../../actions/app-actions';import { storeSession, refreshSession } from '../../../actions/session-actions';import I18n from 'react-native-i18n';import {  KEYCHAIN_RESET,  KEYCHAIN_GET,  KEYCHAIN_RESULT} from '../../../constants/action-types';import { validatePassword, createCustomError, serverError } from '../../../services/utils';const delay = (ms) => new Promise(resolve => setTimeout(resolve, ms))export function * ChangePasswordWatcher( api, action ) {        yield fork( ChangePasswordFormWatcher, api, action );}export function * ChangePasswordFormWatcher(api, action){  while (true) {    yield race({      changePasswordProcess: call(ChangePasswordStart, api),      cancel: take(['CHANGE_PASSWORD_PASSWORD_RESET'])    });    //yield put( loader('hide') );        yield put( loader('hide') );  }}/** * Change Password Sagas starter * * @param {function} api - api object * @param {object} action - action from dispatch * @returns */export function * ChangePasswordStart(api, action) {    try {            while (true) {                const { formData } = yield take('CHANGE_PASSWORD_FORM_SUBMIT');                                let oldPassword = formData.oldPassword;                                let newPassword = formData.newPassword;                                let newPasswordConfirmation = formData.newPasswordConfirmation;                                yield put({                                type: 'CHANGE_PASSWORD_FORM_VALID'                              });                                const validate = validateForm( 'changePasswordForm', formData );                                if ( validate.valid ) {                                        yield put( actionCreators.submitChangePasswordFormValid() );                                        yield put( loader('show') );                                        let newPasswordResponse = yield call( api.setChangePassword, oldPassword, newPassword);                    yield put( loader('hide') );                    if ( !newPasswordResponse.ok ) {                                            let errors = serverError(newPasswordResponse);                                            console.log(errors);                                      console.log('errors newPasswordResponse');                                      yield put( showModalError({ error: errors }));                                      yield put( actionCreators.submitNewPasswordFormFailed( errors ) );                                        //  return false;                                        }                                        else {                                        yield put({                                            type: KEYCHAIN_GET,                                            // resultAction: ''                                        });                                        const keychain = yield take(KEYCHAIN_RESULT);                    // Save to Keychain                                        yield put( keychainSet({                                            login: keychain.login || false,                                            password: keychain.password || false                                        }) );                            // final screen                                        yield put( redirectTo('thankyou') );                                        yield call( delay, 300 );                                        yield put( actionCreators.changePasswordResetState() );                                    }                                }                                else {                                    yield put( showModalError({ error: validate.errors }));                                    yield put( actionCreators.submitChangePasswordFormFailed( validate.errors ));                                    yield put( actionCreators.changePasswordFailed() );                    //                      yield put( actionCreators.submitFinFormFailed( ret.errors ) );                //                      yield put( actionCreators.registrationFailed());                              }          // Reset login         //  yield call( delay, 300 );        //  yield put( actionCreators.resetState() );        }    } catch (e) {            console.log(e);    }}export function validateForm( formKey, formData ) {  let  ret = {    valid: true,    errors: false  },  schema: {};  switch ( formKey ) {    case 'changePasswordForm':        schema = {                    oldPassword: V.required( validatePassword ),                    newPassword: V.required( validatePassword ),                    newPasswordConfirmation: V.required( R.equals( formData.newPassword ) )                };      break;    default:      break;  }  ret.valid = V.validate( schema, formData );  if ( !ret.valid ) {    ret.errors = V.getErrors( schema, formData );    ret.errors = R.zipObj( R.pluck('property', ret.errors), ret.errors );  }  console.log('isValid: '+ ret.valid.toString());  return ret;}

To comment all Console.log statements not helped

import { select, take, takeLatest, call, put, fork, race } from 'redux-saga/effects';import R from 'ramda';import V from 'o-validator';import * as actionCreators from './actions';import { redirectTo, showModalError, showModal, showOtp, closeOtp, errorOtp, loader, keychainSet } from '../../../actions/app-actions';import { storeSession, refreshSession } from '../../../actions/session-actions';import I18n from 'react-native-i18n';import {  KEYCHAIN_RESET,  KEYCHAIN_GET,  KEYCHAIN_RESULT} from '../../../constants/action-types';import { validatePassword, createCustomError, serverError } from '../../../services/utils';const delay = (ms) => new Promise(resolve => setTimeout(resolve, ms))export function * changePasswordScreenWatcher( api, action ) {        yield fork( ChangePasswordFormWatcher, api, action );}export function * ChangePasswordFormWatcher(api, action){  while (true) {    yield race({      changePasswordProcess: call(ChangePasswordStart, api),      cancel: take(['CHANGE_PASSWORD_PASSWORD_RESET'])    });    //yield put( loader('hide') );        yield put( loader('hide') );  }}/** * Change Password Sagas starter * * @param {function} api - api object * @param {object} action - action from dispatch * @returns */export function * ChangePasswordStart(api, action) {    try {            while (true) {                const { formData } = yield take('CHANGE_PASSWORD_FORM_SUBMIT');                                let oldPassword = formData.oldPassword;                                let newPassword = formData.newPassword;                                let newPasswordConfirmation = formData.newPasswordConfirmation;                                yield put({                                type: 'CHANGE_PASSWORD_FORM_VALID'                              });                                const validate = validateForm( 'changePasswordForm', formData );                                if ( validate.valid ) {                                        yield put( actionCreators.submitChangePasswordFormValid() );                                        yield put( loader('show') );                                        let newPasswordResponse = yield call( api.setChangePassword, oldPassword, newPassword);                    yield put( loader('hide') );                    if ( !newPasswordResponse.ok ) {                                            let errors = serverError(newPasswordResponse);                                            //console.log(errors);                                      //console.log('errors newPasswordResponse');                                      yield put( showModalError({ error: errors }));                                      yield put( actionCreators.submitNewPasswordFormFailed( errors ) );                                        //  return false;                                        }                                        else {                                        yield put({                                            type: KEYCHAIN_GET,                                            // resultAction: ''                                        });                                        const keychain = yield take(KEYCHAIN_RESULT);                    // Save to Keychain                                        yield put( keychainSet({                                            login: keychain.login || false,                                            password: keychain.password || false                                        }) );                            // final screen                                        yield put( redirectTo('thankyou') );                                        yield call( delay, 300 );                                        yield put( actionCreators.changePasswordResetState() );                                    }                                }                                else {                                    yield put( showModalError({ error: validate.errors }));                                    yield put( actionCreators.submitChangePasswordFormFailed( validate.errors ));                                    yield put( actionCreators.changePasswordFailed() );                    //                      yield put( actionCreators.submitFinFormFailed( ret.errors ) );                //                      yield put( actionCreators.registrationFailed());                              }          // Reset login         //  yield call( delay, 300 );        //  yield put( actionCreators.resetState() );        }    } catch (e) {            //console.log(e);    }}export function validateForm( formKey, formData ) {  let ret = {    valid: true,    errors: false  };  switch ( formKey ) {    case 'changePasswordForm':        schema = {                    oldPassword: V.required( validatePassword ),                    newPassword: V.required( validatePassword ),                    newPasswordConfirmation: V.required( R.equals( formData.newPassword ) )                };      break;    default:      break;  }  ret.valid = V.validate( schema, formData );  if ( !ret.valid ) {    ret.errors = V.getErrors( schema, formData );    ret.errors = R.zipObj( R.pluck('property', ret.errors), ret.errors );  }  //console.log('isValid: '+ ret.valid.toString());  return ret;}

Programmatically Restart a React Native App

$
0
0

Is it possible to programmatically restart a React Native app without writing any native code?

For instance, I know from the answer to this question that I can restart an Android app with:

Intent i = getBaseContext().getPackageManager()         .getLaunchIntentForPackage( getBaseContext().getPackageName() );i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);startActivity(i);

Can I do the same with React Native?


CDN: trunk URL couldn't be downloaded in certain React Native project when running "pod install"?

$
0
0

I have this react native project that im working with multiple computers, in my MacBook everything works fine, when I run "pod install" after running "npm install" the pods project is created successfully, in the other hand when I do the same in my desktop I get this following error:

enter image description here

Ive tried installing pods for other projects and everything works fine, the problem is with this project in particular.

UPDATAE:

Thanks for your comments, for you to know:

after running:

pod repo remove trunkpod install

This is what I get:

enter image description here

This is my package.json:

{"name": "aksystems","version": "3.9.8","description": "","author": "","private": true,"scripts": {"start": "react-native start","test": "jest","lint": "eslint .","ios": "cd ios/ && rm -rf Pods/ && rm -rf Podfile.lock && pod install && cd ../ && react-native run-ios","android": "cd android/ && ./gradlew clean && cd ../ && react-native run-android","build:ios": "node node_modules/react-native/local-cli/cli.js bundle --entry-file='index.js' --bundle-output='./ios/mstore/main.jsbundle' --dev=false --platform='ios' --assets-dest='./ios'","setup": "./scripts/setup.sh","setup:android": "./scripts/setup_android.sh","reset": "./scripts/reset.sh","postinstall": "patch-package && npx jetify"  },"dependencies": {"@babel/plugin-proposal-class-properties": "^7.5.5","@babel/plugin-proposal-decorators": "^7.4.4","@invertase/react-native-apple-authentication": "^0.1.1","@react-native-community/async-storage": "^1.5.1","@react-native-community/netinfo": "5.0.1","@react-native-community/viewpager": "^3.3.0","@react-native-firebase/app": "^6.0.4","@react-native-firebase/auth": "^6.0.4","api-ecommerce": "0.0.34","base-64": "^0.1.0","currency-formatter": "^1.5.4","deprecated-react-native-listview": "0.0.6","firebase": "^7.9.1","firebase-admin": "^8.9.2","glob": "^7.1.6","html-entities": "^1.2.1","jetifier": "^1.6.3","lodash": "^4.17.15","moment": "^2.24.0","native-base": "^2.13.8","oauth-1.0a": "^2.2.6","patch-package": "^6.1.2","postinstall-postinstall": "^2.0.0","react": "16.9.0","react-native": "0.61.5","react-native-admob": "^2.0.0-beta.6","react-native-animatable": "^1.3.2","react-native-app-intro-slider": "^3.0.0","react-native-apple-authentication": "https://github.com/ton44079/react-native-apple-authentication","react-native-camera": "git+https://git@github.com/react-native-community/react-native-camera.git","react-native-clean-form": "^0.5.0","react-native-collapsible": "^1.4.0","react-native-country-picker-modal": "^1.10.0","react-native-credit-card-input": "^0.4.1","react-native-date-picker": "^2.7.7","react-native-drawer": "^2.5.1","react-native-facebook-account-kit": "^2.1.0","react-native-fbsdk": "^1.1.1","react-native-fluid-slider": "^1.0.2","react-native-gesture-handler": "^1.6.0","react-native-image-picker": "^2.3.1","react-native-image-zoom-viewer": "^2.2.26","react-native-keyboard-aware-scroll-view": "0.9.1","react-native-linear-gradient": "^2.5.5","react-native-localization": "^2.1.4","react-native-masked-text": "^1.12.4","react-native-modalbox": "2.0.0","react-native-onesignal": "3.5.0","react-native-paper": "3.4.0","react-native-picker-select": "^6.3.3","react-native-radio-buttons": "^1.0.0","react-native-reanimated": "^1.7.0","react-native-render-html": "^4.1.2","react-native-restart": "^0.0.13","react-native-screens": "^2.0.0-alpha.22","react-native-scrollable-tab-view": "1.0.0","react-native-snap-carousel": "^3.8.0","react-native-star-rating": "^1.1.0","react-native-store-rating": "^1.0.1","react-native-swipe-list-view": "^2.0.0","react-native-swiper": "^1.6.0-nightly.5","react-native-tab-view": "^2.13.0","react-native-vector-icons": "^6.6.0","react-native-video": "^5.0.2","react-native-webview": "8.0.1","react-navigation": "4.0.10","react-navigation-stack": "^1.10.3","react-navigation-tabs": "^2.6.2","react-redux": "7.1.0","redux": "4.0.5","redux-actions": "^2.6.5","redux-persist": "5.10.0","redux-thunk": "^2.3.0","reselect": "^4.0.0","tcomb-form-native": "^0.6.20","tipsi-stripe": "^7.5.1","urijs": "^1.19.1","url": "^0.11.0","url-parse": "^1.4.7","util": "^0.12.1","uuid": "^3.3.2","validate.js": "^0.13.1","wpapi": "^1.2.1"  },"devDependencies": {"@babel/core": "7.6.2","@babel/runtime": "7.6.2","@react-native-community/eslint-config": "^0.0.5","babel-jest": "24.9.0","babel-plugin-transform-remove-console": "^6.9.4","eslint": "6.5.1","eslint-config-airbnb": "^18.0.1","eslint-plugin-import": "^2.19.1","eslint-plugin-jsx-a11y": "^6.2.3","eslint-plugin-react-hooks": "^2.3.0","jest": "24.9.0","metro-react-native-babel-preset": "0.57.0","react-test-renderer": "16.10.2","reactotron-react-native": "4.0.2","reactotron-redux": "3.1.2"  },"jest": {"preset": "react-native","setupFiles": ["./node_modules/react-native-gesture-handler/jestSetup.js"    ]  }}

And podfile:

platform :ios, '9.0'#require_relative '../node_modules/@react-native-community/cli-platform-ios/native_modules'require_relative '../node_modules/@react-native-community/cli-platform-ios/native_modules'target 'aksystems' do  # Pods for mstore  pod 'FBLazyVector', :path => "../node_modules/react-native/Libraries/FBLazyVector"  pod 'FBReactNativeSpec', :path => "../node_modules/react-native/Libraries/FBReactNativeSpec"  pod 'RCTRequired', :path => "../node_modules/react-native/Libraries/RCTRequired"  pod 'RCTTypeSafety', :path => "../node_modules/react-native/Libraries/TypeSafety"  pod 'React', :path => '../node_modules/react-native/'  pod 'React-Core', :path => '../node_modules/react-native/'  pod 'React-CoreModules', :path => '../node_modules/react-native/React/CoreModules'  pod 'React-Core/DevSupport', :path => '../node_modules/react-native/'  pod 'React-RCTActionSheet', :path => '../node_modules/react-native/Libraries/ActionSheetIOS'  pod 'React-RCTAnimation', :path => '../node_modules/react-native/Libraries/NativeAnimation'  pod 'React-RCTBlob', :path => '../node_modules/react-native/Libraries/Blob'  pod 'React-RCTImage', :path => '../node_modules/react-native/Libraries/Image'  pod 'React-RCTLinking', :path => '../node_modules/react-native/Libraries/LinkingIOS'  pod 'React-RCTNetwork', :path => '../node_modules/react-native/Libraries/Network'  pod 'React-RCTSettings', :path => '../node_modules/react-native/Libraries/Settings'  pod 'React-RCTText', :path => '../node_modules/react-native/Libraries/Text'  pod 'React-RCTVibration', :path => '../node_modules/react-native/Libraries/Vibration'  pod 'React-Core/RCTWebSocket', :path => '../node_modules/react-native/'  pod 'React-cxxreact', :path => '../node_modules/react-native/ReactCommon/cxxreact'  pod 'React-jsi', :path => '../node_modules/react-native/ReactCommon/jsi'  pod 'React-jsiexecutor', :path => '../node_modules/react-native/ReactCommon/jsiexecutor'  pod 'React-jsinspector', :path => '../node_modules/react-native/ReactCommon/jsinspector'  pod 'ReactCommon/jscallinvoker', :path => "../node_modules/react-native/ReactCommon"  pod 'ReactCommon/turbomodule/core', :path => "../node_modules/react-native/ReactCommon"  pod 'Yoga', :path => '../node_modules/react-native/ReactCommon/yoga'  pod 'DoubleConversion', :podspec => '../node_modules/react-native/third-party-podspecs/DoubleConversion.podspec'  pod 'glog', :podspec => '../node_modules/react-native/third-party-podspecs/glog.podspec'  pod 'Folly', :podspec => '../node_modules/react-native/third-party-podspecs/Folly.podspec'  pod 'Google-Mobile-Ads-SDK'  pod 'react-native-date-picker', :path => '../node_modules/react-native-date-picker'  pod 'react-native-image-picker', :path => '../node_modules/react-native-image-picker'  pod 'Stripe', '~> 14.0.0'  pod 'tipsi-stripe', :path => '../node_modules/tipsi-stripe'  pod 'react-native-onesignal', :path => '../node_modules/react-native-onesignal'  target 'aksystemsTests' do    inherit! :search_paths    # Pods for testing  end  use_native_modules!endtarget 'OneSignalNotificationServiceExtension' do  pod 'OneSignal', '>= 2.9.3', '< 3.0'end

As you said, Ive seen in various SO questions and GitHub posts that might be a network issue but as I told you another Pod projects work pretty well, the pods versions are the same (last) and both machines are running over the same network.

Getting "undefined is not an object" trying to pass navigator prop to grandchildren

$
0
0

My React Native app structure is as follows: a Drawer navigator, which contains a BottomTabNavigator, which itself contains 3 tabs (each of them Stack navigators). My issue comes when trying to pass the drawer navigation prop to one of the BottomTabNavigator stacks. I am trying to pass it to a custom component in the headerLeft of one of my Stacks, however I get an "Undefined is not an object" when calling navigation.openDrawer within the headerLeft component.

App.js

<NavigationContainer ref={containerRef} initialState={initialNavigationState}><Drawer.Navigator><Drawer.Screen name="Feed" component={BottomTabNavigator} options={{swipeEnabled: false}} /><Drawer.Screen name="Settings" component={SettingsStack} options={{swipeEnabled: false}} /></Drawer.Navigator></NavigationContainer>

BottomTabNavigator.js

const BottomTab = createBottomTabNavigator();function HomeStack({ navigation }) {  return (<MyHomeStack.Navigator screenOptions={{headerShown: true,    headerLeft: ({navigation}) => <HamburgerIcon {...navigation} />    }}><MyHomeStack.Screen name="home" component={HomeScreen}/></MyHomeStack.Navigator>  );{...MessageStack Code}{...ProfileStack Code}export default function BottomTabNavigator({ navigation, route }) {return (<BottomTab.Navigator initialRouteName={INITIAL_ROUTE_NAME} ><BottomTab.Screen        name="Home"        component={HomeStack}        options={{title: 'Feed'}}      /><BottomTab.Screen        name="Messages"        component={MessagesStack}        options={{title: 'Messages'}}      /><BottomTab.Screen        name="Profile"        component={ProfileStack}        options={{title: 'Profile'}}      /></BottomTab.Navigator>  );}

HamburgerIcon.js

function HamburgerIcon(navigation) {    return (<TouchableOpacity        style={{            width: 30,            height: 30,            marginLeft: 10        }}        onPress={(navigation) => navigation.openDrawer()} ><SafeAreaView style={{alignSelf: "center"}}><Ionicons name='ios-menu' size={28} color='#000000'/></SafeAreaView></TouchableOpacity>    );}export default HamburgerIcon;

How to pass data between react native screens?

$
0
0

Hey I am new to react native. So basically I have a stack navigator with two screen option: Screen 1 (Default) and Screen2. I already set up a button so that when pressed it will take me to Screen 2. So in Screen1 I have an array displayed as scrollview component. Now when i press the button to go to screen2 I want to pass some of the array values to that screen2 component. What is the best way to do it? Thank you :)

I am really new so my attempts are kinda dumb. I tried importing the Screen1 component and calling the array values via this.state but no access.

I don't get the result of my promice despite using await

$
0
0

My function looks like this:

async function getPlaceForecast(lat, long) {//var response;var day5forecast = 'http://api.openweathermap.org/data/2.5/forecast?lat='+ lat +'&lon='+ long +'&appid='+ apikey;try {    const request = new Request(tmp2, {        method: 'get'    })    let response = await fetch(request)        .then(value => {            console.log("than", value.json());            return value//.json();        })        .catch(function (error) {            console.error(error);        });}catch{}//return response;

}

This is the result:

'than', { _40: 0, _65: 0, _55: null, _72: null }

And this is the result without using .json() :

'than', { type: 'default', status: 200, ok: true, statusText: undefined, headers: { map: { 'access-control-allow-methods': 'GET, POST','access-control-allow-credentials': 'true','access-control-allow-origin': '*','x-cache-key': '/data/2.5/forecast?lat=28.35&lon=-14.05', connection: 'keep-alive','content-length': '14383','content-type': 'application/json; charset=utf-8', server: 'openresty' } }, url: 'http://api.openweathermap.org/data/2.5/forecast?lat=28.349414&lon=-14.046311&appid=', _bodyInit: { _data: { size: 14383, offset: 0, blobId: '2dbf82c5-5d28-47db-9034-7f239bf8290a' } }, _bodyBlob: { _data: { size: 14383, offset: 0, blobId: '2dbf82c5-5d28-47db-9034-7f239bf8290a' } } }

What did I do wrong?

I don't get the result of my promise despite using await

$
0
0

My function looks like this:

async function getPlaceForecast(lat, long) {//var response;var day5forecast = 'http://api.openweathermap.org/data/2.5/forecast?lat='+ lat +'&lon='+ long +'&appid='+ apikey;try {    const request = new Request(tmp2, {        method: 'get'    })    let response = await fetch(request)        .then(value => {            console.log("than", value.json());            return value//.json();        })        .catch(function (error) {            console.error(error);        });}catch{}//return response;

}

This is the result:

'than', { _40: 0, _65: 0, _55: null, _72: null }

And this is the result without using .json() :

'than', { type: 'default',status: 200,ok: true,   statusText: undefined,  headers:   { map:     { 'access-control-allow-methods': 'GET, POST','access-control-allow-credentials': 'true','access-control-allow-origin': '*','x-cache-key': '/data/2.5/forecast?lat=28.35&lon=-14.05',        connection: 'keep-alive','content-length': '14383','content-type': 'application/json; charset=utf-8',         server: 'openresty' } },  url: 'http://api.openweathermap.org/data/2.5/forecast?lat=28.349414&lon=-14.046311&appid=<mykey>',  _bodyInit:    { _data:     { size: 14383,       offset: 0,   blobId: '2dbf82c5-5d28-47db-9034-7f239bf8290a' } },  _bodyBlob:   { _data:      { size: 14383,       offset: 0,        blobId: '2dbf82c5-5d28-47db-9034-7f239bf8290a' } } }

What did I do wrong?

How to preview files inside an app component using react-native

$
0
0

I'm trying to preview files inside my component. Currently I'm using react-native-file-viewer, which can't open the files inside the component and takes up the whole screen. Is there any way to achieve this in react-native?

<SafeAreaView style={{flex: 1, backgroundColor: 'white'}}><Grid><Col size={30}>      ...</Col><Col size={70} style={{ backgroundColor: '#00CE9F'}}>      //Preview should go here</Col></Grid></SafeAreaView>

The preview should be displayed on the right side.ScreenshotThis is the current preview:Current Preview

Command PhaseScriptExecution failed with a nonzero exit code RealmJS

$
0
0

I am trying to run the application within react-native using realmjs but I am facing this error, I am searching this from the last 2 days but no luck please help.

Using Node.js v14.2.0internal/modules/cjs/loader.js:1023  throw err;  ^Error: Cannot find module '/Users/salman/Documents/Bitbucket'    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:1020:15)    at Function.Module._load (internal/modules/cjs/loader.js:890:27)    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12)    at internal/main/run_main_module.js:17:47 {  code: 'MODULE_NOT_FOUND',  requireStack: []}

Warning: ToastAndroid is not supported on this platform. error with react native

$
0
0

I am getting this error on react native IOS,

- node_modules/expo/build/logs/LogSerialization.js:166:14 in _captureConsoleStackTrace- node_modules/expo/build/logs/LogSerialization.js:41:24 in serializeLogDataAsync- ... 9 more stack frames from framework internals

import { ToastAndroid } from 'react-native'ToastAndroid.show('Somthing!', ToastAndroid.SHORT);

React native - build application

$
0
0

I downloaded the react app via npx react-native init AwesomeProject. The application ran for the first time. After stopping through the terminal, the build application pauses and thus see the screen is a few minutes and does not continue.For Android everything is OK. This "mistake" is just for ios.

Anyone have any idea?Thank you

screen shot

Get current controller in react native iOS?

$
0
0

I am using the iOS native framework in the react native app. I want to pass the UIViewController in the SDK parameter when clicking the Button that was created in the JS.

func load() { //**navigate to SDK screen**HKSDKController.load(withMainPage: false, andParentViewController: self)    //HKSDKController.load(withMainPage: false, andParentViewController: UIViewController())}

When I try to pass the “self”, I can’t able to navigate to the SDK controller. How to do that?

Input.js:

load = () => { NativeModules.ViewController.load(); }

I can able to call the load() from js to ViewController. But I can't navigate through view controller to SDK.

In android, there is an option to get CurrentActivity. But what’s the way to pas self and navigate.

final Activity activity = getCurrentActivity();

I want to pass the UIViewController in the SDK parameter(andParentViewController).

No known class method for selector 'labelColor' - react-native-image-crop-picker - for react-native iOS

$
0
0

I am using react-native-image-crop-picker library within react-native applicationVersion details

react-native version: 59.10 react-native-image-crop-picker: 0.25.3 xcode: 10.1

While execution of code I am getting the error QBImagePicker/QBAssetsViewController.m:198:31: No known class method for selector 'labelColor'

195    // Info label196    UIColor *labelColor = [UIColor blackColor];197    if (@available(iOS 13.0, *)) {198        labelColor = [UIColor labelColor];199    }

I have tried to upgrade library version but issue is still there. can anyone please help

Thank you in advance

Styling React Native Picker

$
0
0

I'm attempting to style the text color of the items in a React Native picker. I've only been working in iOS so far, but if I could find a cross-platform solution that'd be awesome.

I've tried the following things:

Styling color on Picker

<Picker style={{color:'white'}} ...etc >

Styling color on Picker Items

<Picker.Item style={{color:'#fff'}} label={'Toronto'} value={'Toronto'} />

I've also seen some examples of adding a color property, so I tried this

<Picker.Item color='white' label={'Toronto'} value={'Toronto'} />

At a total loss here. Thanks for any insight!

EDIT:Here's a solution - use itemStyle prop in the Picker element. I believe this is iOS only.

<Picker itemStyle={{color:'white'}} ><Picker.Item color='white' label={'Toronto'} value={'Toronto'} /><Picker.Item  label={'Calgary'} value={'Calgary'} /></Picker>
Viewing all 16558 articles
Browse latest View live