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

react native axios request not working in IOS simulator

$
0
0

I am trying to getting data from API using axios.

This is my code that makes a get request :

export const loadBloodGroups = () => {    return (dispatch) => {        dispatch({ type: LOADING_BLOOD });        const url = `http://www.example.org/api/bloodgroup/getusersbloodgroup`;        axios.get(url)        .then(response => loadingSuccess(dispatch, response))        .catch(error => loadingFail(dispatch, error));    };};const loadingFail = (dispatch, error) => {    console.log(error);    dispatch({         type: LOADING_BLOOD_FAIL,        payload: error    });};const loadingSuccess = (dispatch, response) => {    dispatch({        type: LOADING_BLOOD_SUCCESS,         payload: response    });}; 

info.plist setup for http :

enter image description here

It works fine in android emulator, but IOS simulator is not working.

In my browser debug console it shows :

enter image description here

and Mac terminal it shows :

enter image description here

Can anybody tell me, where I made mistake ? or should I need to do any other configuration for IOS?

My platform:

  • OS: Mac 10.13
  • node: 10.7
  • npm: 6.3.0
  • react: 16.4.1
  • react-native: 0.55

On scroll React Native Animated do the animation but flickering

$
0
0

In my react native app I'm trying to animate opacity of a View.When I scroll, I saw the animation do the job, but it’s flickering at the same time. I don’t know why.

Video example : https://cdn.discordapp.com/attachments/102861040538120192/560165613092339734/video.mov

Here is the code I made

const Scrollable = () => {  const largeHeaderSize = useState({    height: 0,    y: 0  });  const animatedValueScrollY = new Animated.Value(largeHeaderSize.height);  const [scrollY, setScrollY] = useState(0);  const headerOpacity = animatedValueScrollY.interpolate({    inputRange: [0, largeHeaderSize.height],    outputRange: [1, 0],    extrapolate: "clamp"  });  return (<SafeAreaView><Animated.View        style={{        borderBottomWidth:          scrollY >= largeHeaderSize.height ? StyleSheet.hairlineWidth : 0      }}><View><Animated.View style={{ zIndex: 1, opacity: headerOpacity }}><Text>Title</Text></Animated.View></View></Animated.View><Animated.ScrollView        onScroll={Animated.event(          [{ nativeEvent: { contentOffset: { y: animatedValueScrollY } } }],          {            useNativeDriver: true,            listener: event => setScrollY(event.nativeEvent.contentOffset.y)          }        )}        scrollEventThrottle={16}        contentInset={{          top: 0,          bottom: 50        }}        contentOffset={{          y: 0        }}      /></SafeAreaView>  );};

How I can I solve that?

React native orientation is not working || locking on IOS

$
0
0

I created an app with React-native. All pages I made are designed for portrait mode except 1 page. The page accessibility comes from a button onPress then navigates to the page, so I can't lock orientation on Xcode

I installed this package and I can run it on android perfectly

import Orientation from 'react-native-orientation';

When I tried it on IOS simulator on every page it can turns orientation to landscape.

I put this line in every pages componentdidmount but nothing changes.

componentDidMount() {    Orientation.lockToPortrait()...}

What should I do?

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;}

Keyboard alignment issue with multiline text input

$
0
0

I have also used KeyboardAvoidingView, this aligns the keyboard properly if its only single line but not with multiline.

<KeyboardAvoidingView behavior="position"><TextInput     placeholder='input 1'     placeholderTextColor='gray'     multiline={true}     onContentSizeChange={(e) => console.log(e.nativeEvent.contentSize)}     value='text 1'    /><TextInput     placeholder='input 2'     placeholderTextColor='gray'     multiline={true}     onContentSizeChange={(e) => console.log(e.nativeEvent.contentSize)}     value='text 2'    /></KeyboardAvoidingView>

Is there any way to align the keyboard properly with multiline textInputs in react native?

React native - how to ignore silent mode and play sound/send push notification?

$
0
0

I'd like to make an app with React Native that lets you chat with your significant other, and totally ignores silent mode. I.e., even if your phone is in silent mode, this app will still play sounds to alert you of new messages and send you push notifications. The idea is that you can put your phone on silent to block messages from friends, coworkers, etc, but your significant other can still message you and you can hear when they and only they send you a message.

How can you do this on React Native? I'm assuming that this is possible (at the very least on iOS) as the Apple Watch is able to make your phone peep even if it's on silent (unless this is a top secret feature that only Apple developers are allowed to use).

How to read from AsyncStorage in native code (Java, ObjectiveC/Swift)

$
0
0

I have a background service I wrote in native (Java/ObjectiveC) that needs to access data from AsyncStorage in react native. I would like to know if there is an easy way to get this value directly from the native code instead of having to pass it manually through a bridge method.

Since this is a background service that runs even if the app is not running (in Android), it can not call the Javascript code when it needs this data. I could work around it (by setting it in native at the same time I set it in AsyncStorage) but it would be a lot more work.

React Native - good practice: SegmentedControlIOS with ListView

$
0
0

What are the best practices in implementing SegmentedControllIOS with ListView? I tried three solutions, all examples contain SegmentedControllIOS with two segments and two ListView. I invite you to discuss performance of this three (maybe someone could propose other, better solution). From my perspective examples are given in order from most efficient.

1. Two independent dataSource, one ListView (change dataSource of ListView)

class Example extends Component {  constructor(props) {    super(props);    this.state = {      ds1: new ListView.DataSource({ rowHasChanged: (r1, r2) => r1 !== r2,}),      ds2: new ListView.DataSource({ rowHasChanged: (r1, r2) => r1 !== r2,}),      index: 0,    };  }  render() {    return (<View><SegmentedControlIOS          selectedIndex={this.state.index}          values={['ds1', 'ds2']}          onChange={() => this.setState({index: (this.state.index+1)%2})}        /><ListView dataSource={this.state.index ? this.state.ds2 : this.state.ds1} /></View>    );  }}

2. Two independent dataSource and two independent ListView

class Example extends Component {  constructor(props) {    super(props);    this.state = {      ds1: new ListView.DataSource({ rowHasChanged: (r1, r2) => r1 !== r2,}),      ds2: new ListView.DataSource({ rowHasChanged: (r1, r2) => r1 !== r2,}),      index: 0,    };  }  render() {    return (<View><SegmentedControlIOS          selectedIndex={this.state.index}          values={['ds1', 'ds2']}          onChange={() => this.setState({index: (this.state.index+1)%2})}        />        {this.state.index === 0 ?          (<ListView dataSource={this.state.ds1} />)        :          (<ListView dataSource={this.state.ds2} />)        }</View>    );  }}

3. One dataSource, cloneWithRows on dataSource on change index

class Example extends Component {  constructor(props) {    super(props);    this.state = {      ds: new ListView.DataSource({ rowHasChanged: (r1, r2) => r1 !== r2,}),      ds1: ['some', 'data'],      ds2: ['some', 'other', 'data'],      index: 0,    };    this.onChange = this.onChange.bind(this);  }  onChange() {    this.setState({      ds: this.state.ds.cloneWithRows(this.state.index ? this.ds1 : this.ds2),      index: (this.state.index+1)%2,    })  }  render() {    return (<View><SegmentedControlIOS          selectedIndex={this.state.index}          values={['ds1', 'ds2']}          onChange={this.onChange}        /><ListView dataSource={this.state.ds} /></View>    );  }}

React-Native error ld: library not found for -lBVLinearGradient

$
0
0

Installed 'react-native-lienar-gradient' library in my new react-native project.

Added pod 'BVLinearGradient', :path => '../node_modules/react-native-linear-gradient' in Podfile

Performed pod install in ios directory

Xcode build gives the following error:

ld: warning: directory not found for option '-L-L/Users/pavneet/Library/Developer/Xcode/DerivedData/Krowym-fttolxdorzfwjbcgjwmxijsnufkv/Build/Products/Debug-iphonesimulator/BVLinearGradient'ld: library not found for -lBVLinearGradientclang: error: linker command failed with exit code 1 (use -v to see invocation)

Error in Xcode

Tried deleting Podfile.lock, cleaning xcode build, manually linking library by react-native link command, deleting Derived data folder

Also tried by adding libBVLinearGradient.a on Build Phases -> Link Binary With Libraries

Environment

react-native:0.63.2

react-native-linear-gradient:2.5.6

Show the name of nearby peripheral devices in react-native-ble-manager

$
0
0

I am stuck in an issue where, in react-native-ble-manager, I am not able to show the name of nearby peripheral devices.

Got ble peripheral

{"advertising": {"isConnectable": true,"manufacturerData": {"CDVType": "ArrayBuffer","bytes": [Array      ],"data": "AgEaAgoIC/9MABAGPB6sswN2AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA="    },"serviceData": {},"serviceUUIDs": [],"txPowerLevel": 8  },"id": "69:DC:FB:ED:1B:B1","name": null,"rssi": -47}

Exclude some .js file while building apk : react-native

$
0
0

When building an apk/aab for react-native project, How to exclude some file to reduce the app size ?

Can't build for target iOS device in arm64 [closed]

Is there a way to run python scripts locally in a react native app [closed]

$
0
0

I got some python modules compatible with iOS. How can I make it run on react-native applications without using a server?

React Native - npx react-native run-ios doesn't work after initializing the project

$
0
0

After reading https://reactnative.dev/docs/environment-setup, I created a react-native project using npx react-native init ***.

It was successful, so, I tried to run the project using npx react-native run-ios, and got the below error:

** BUILD FAILED **The following build commands failed:    CompileC /Users/loser/Library/Developer/Xcode/DerivedData/test0205-dasunahpjpavelgmslwgmvjhesxy/Build/Intermediates.noindex/Pods.build/Debug-iphonesimulator/Flipper.build/Objects-normal/x86_64/FlipperRSocketResponder.o /Users/loser/Documents/projects/test0205/ios/Pods/Flipper/xplat/Flipper/FlipperRSocketResponder.cpp normal x86_64 c++ com.apple.compilers.llvm.clang.1_0.compiler(1 failure)

Build input file cannot be found in React-native lib

$
0
0

So let me tell you what I am doing first.

I have a RN app/project which I am converting to npm library.

I build a dist folder where I build and copy my Android, ios and Js file

for iOS, I run this command

npm run "ios:lib": "rsync -r ./ios --exclude='.*' --exclude='xyzClientMobile' --exclude='xyzClientMobile.xcworkspace'--exclude='xyzClientMobile-tvOS' --exclude='xyzClientMobile-tvOSTests'  --exclude='xyzClientMobileTests' --exclude='Pods' --exclude='Podfile.lock'  ./dist && npm run ios:podspec",

Now all good until I try to build my app in IOS, where it gives folllowing error

Build input file cannot be found: 'main.m' (in target 'xyz-mobile' from project 'Pods')

I am not sure how to fix, but when I search for main.m reference in my project from which I was creating lib, I see its reference in multiple places inside .xcodeproj > project.pbxproj

some thing like this

13B08FB71A68208900A75B9A /* main.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = main.m; path = xyzClientMobile/main.m; sourceTree = "<group>"; };

Any idea how I can fix it?


Build error: 'React/RCTBridge.h' file not found when adding Notification Service Extention

$
0
0

My RN app is always having a build failed whenever I added Notification Service Extension for iOS. The error is just like shown below:

'React/RCTBridge.h' file not foundFailed to emit precompiled header '/path/Build/Intermediates.noindex/PrecompiledHeaders/bridging-path.pch' for bridging header '/Bridging-Header-path.h

Have tried lots of solutions found online, but none of them seems to work in my cases. I have tried apply some simple cleansing such as:

  • yarn clean
  • clean build and re-build
  • remove pod and re-install it
  • remove derivedData
  • quit and open XCode
  • restart my MAC

Not sure what is needed because the failure is on the Notification Service target. Not the main app itself. I have tried to follow the implementation guide, but everywhere is the same, very straight forward and simple. just add the target & create app ID and then that's it. Nothing is mentioned about some adjustment in another files perhaps like do I need to add extra on the info.plist or anything else?

I am currently using XCode 12.4.

Any idea of what should have been done to avoid this issue?

ScrollView has a width and height that overlaps it's child elements

$
0
0

I have in my render() a ScrollView which contains a TouchableOpacity(or other with onPress) that cannot be pressed because it is overlapped by the ScrollView itself. I only detect how is it not pressed only when showing the Inspector which reveals parent ScrollView has a width and height that overlaps the TouchableOpacity

React Native version:System:OS: macOS 11.4CPU: (4) x64 Intel(R) Core(TM) i5-5250U CPU @ 1.60GHzMemory: 28.64 MB / 4.00 GBShell: 3.2.57 - /bin/bashBinaries:Node: 14.17.0 - /usr/local/bin/nodeYarn: Not Foundnpm: 6.14.13 - /usr/local/bin/npmWatchman: Not FoundManagers:CocoaPods: 1.10.1 - /Users/huulinh/.rvm/gems/ruby-2.6.3/bin/podSDKs:iOS SDK:Platforms: iOS 14.5, DriverKit 20.4, macOS 11.3, tvOS 14.5, watchOS 7.4Android SDK: Not FoundIDEs:Android Studio: Not FoundXcode: 12.5/12E262 - /usr/bin/xcodebuildLanguages:Java: 1.8.0_144 - /usr/bin/javacnpmPackages:@react-native-community/cli: Not Foundreact: 17.0.1 => 17.0.1react-native: 0.64.1 => 0.64.1react-native-macos: Not FoundnpmGlobalPackages:react-native: Not FoundSimulator/Device:iPhone 6

enter image description hereenter image description here

iPhone cannot communicate with dockerized server on localhost

$
0
0

I have a docker-compose.yml that starts a server

version: '3.3'services:  backend:    image: ***    ports:      - '8080:80'    environment:      BASE_URL: http://localhost:8080      DB_URL: jdbc:postgresql://db/project      WEB_BASE_URL: http://localhost:3000    restart: always  db:    ***    restart: always

Now I want the React native app running on an iPhone via xCode to communicate with this server

iPhone is connected via USB, Xcode starts the app on the iPhone.

But a call like await axios.post<LoginResponse>('http://localhost:8080/v1/auth', loginData); cannot be done.

What I have tried with no success

in docker-compose

ports:      - '0.0.0.0:8080:80'with/without  BASE_URL: my.machine.ip.address:8080

And in RN app make calls (instead of localhost) to my.machine.ip.address:8080

Also in Mac system prefrences/sharing/internet sharing (NOT ticked) -> share your connection from Wi-Fi and iPhone USB option Ticked Blockquote

Side note: this initial setting with localhost calls and no port change in docker-compose, works fine in Android (both emulator and device) and the iOS simulator. The problem is only with the real iPhone device

How to disable click and tooltip on user position in iOS with react-native-maps

$
0
0

I'm using react-native-maps for my react-native app.

Everything works fine on Android but during my tests on iOS I realized that the user's position was clickable. I would like to remove this possibility. Or maybe override the tooltips.I didn't find any mention of this issue anywhere on the web or in the documentation, maybe i'm missing a props?

The user tooltips screenshot

Here is my MapView component but nothing is wrong with it in my opinion:

<MapView      ref={this.mapView}      style={styles.map}      customMapStyle={mapStyle}      showsUserLocation={true}      showsMyLocationButton={true}      showsCompass={true}      followsUserLocation={this.state.followUser}      loadingEnabled={true}      toolbarEnabled={true}      zoomEnabled={true}      rotateEnabled={true}>       [...]</MapView>

Thank's by advance, let me know if you need more source or something else!

React Native Image needs to show image on corner

$
0
0

I have an image viewer box in my app box has the size 300px x 300px when I set the image in it and the image has the width and height 100% of this box now I set it resizeMode: 'contain' every image shows in the center of this box, but I need it to show the image in the corner of the box

<View style={{    width: 300,    height: 300}}><Image        source={item.img_url}        style={{            width: '100%',            height: '100%',            resizeMode: 'contain'        }}    /></View>

Check this attachment the logos of companies have the same height but the width is different and the image is always in the corner I need something like this in my scenario.

enter image description here

Viewing all 16907 articles
Browse latest View live