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

How to trigger the UITapGestureRecognizer in Swift through Javascript in React Native?

$
0
0

I have a React Native app that imports a component written in Swift. While the component displays fine, none of the touch events (that worked in the standalone iOS version) work. Currently, my code is organised as follows:

A ViewController that contains the view logic is exposed to React through a UIView class that is exported using RCT_EXTERN_MODULE. The ViewController is where I have put the function to handle the tap gesture. On the React-Native side, I have a sub class of React.Component that renders the view. The view is wrapped in a TouchableWithoutFeedback tag but I assume that also requires a reference to a function that calls my native code, which I am not sure how to provide.


How to promise the data before rendering in functional component React Native?

$
0
0

I'm new to React Native and developing an application. I wrote a code in which when user will press the login button then after successful login, through user's UID i'm getting an attribute of that specific user from Firebase Realtime Database. But when I'm testing it, I'm not getting anything. I have tried everything but nothing is working. may be its problem in my logic please help me out. I'm using latest version of React Native and Firebase.Thank you. This is my Code snippet for login button:

async function _loginBtnClick() {        setLoggedIn(true);        let valid = validate();        if(valid == 1){            setLoggedIn(false);            alert("Email and Password field should not be empty");        }        else if(valid == 2){            setLoggedIn(false);            alert("Email format is not correct. Please input a valid Email");        }        else if (valid == 3){            setLoggedIn(false);            alert("Password should contain at least 6 characters");        }        else if (valid == 4)        {            try {                    await auth().signInWithEmailAndPassword(email,password).then(()=>{                        setID(auth().currentUser.uid.toString());                        alert("ID is"+ id);                     });                    const ref = database().ref(`/users/${id}`);                    const snapshot =  await ref.once('value');                    let type = snapshot.val().userType;                    setUserType(type);                    _storeData(userType);                    setLoggedIn(false);                    navigation.reset({                        index: 0,                        routes: [{ name: 'customerDrawer' }],                    });            } catch (e) {                setLoggedIn(false);                alert(e);            }        }    }

React Native - secureTextEntry Disable IOS 13+ Strong Password behavior

$
0
0

I have an create account form in my app and now on iOS devices running 13+ I'm having an issue where if the the user presses the "done" key while entering a password the normal secure password dots are replaced with the following (see below). How to disable this behavior so it continues to work as it did on older devices?

enter image description here

Hook into events from other apps, such as posting of images, or comments etc

$
0
0

I'm looking to create a mobile app that aggregates information from other apps. For example, every time someone posts an image, comment, post etc using other apps on their mobile like Facebook, Twitter, Instagram, my app would grab that content, or at the very least a unique ID that references that content, an store it in a log.

The app would be 100% opt-in, and transparent. I'm not sure how to best approach this, or if it is even possible, whether something could be done at a low-level on the device, or if it would even be possible using API's (although I don't know if I could subscribe to such events, and even if I could, how would the app know when the post/picture was uploaded from the phone as opposed to a desktop).

React Native - Array of objects in state not updating correctly

$
0
0

I really think I'm going crazy here. So I made a shopping-type app, add to cart and etc.

I have extra comments on each Item which the user can enter any text they want to. The state is correct on "onChangeText" of the input, I checked it with the console. However, when I want to save it (after an edit of the cart), despite the console.log's making sense and that showing the correct state etc, the options changes successfully, but the comments does not. This is very weird as all the other cart array object do change, except the comment. Here is the code:

saveItemCart() {    var index = this.state.cartItems.indexOf(x => x.date === this.state.dateAdded);    let cartItemsArray = this.state.cartItems;    temp = { 'catNumber': this.state.catNumber, 'itemNumber': this.state.itemNumber, 'quantity': this.state.itemQuantity, 'options': this.state.selectedOptions, 'date': this.state.dateAdded, 'comments': this.state.commentsText};    cartItemsArray[index] = temp;    this.setState({ cartItems: cartItemsArray }, () => {        this.updateTotal();        this.setState({ selectedOptions: [], checked: [] })    })}

State:

state = {        ModalItemShown: false,        ModalCartShown: false,        ModalEditShown: false,        isShowToast: false,        isShowToastError: false,        rest_id: this.props.route.params['restaurantid'],        menuData: this.getMenu(),        catNumber: 1,        itemNumber: 1,        dateAdded: null,        commentsText: "",        cartItems: [],        checked: [],        selectedOptions: [],        total: 0,        itemQuantity: 1,    }

Input (inside the render):

<View style={styles.modalOptions}><Input placeholder="..." placeholderTextColor="gray" defaultValue={this.state.commentsText} onChangeText={text => this.setState({ commentsText: text }, () => {console.log(this.state.commentsText)})} /></View><Button shadowless style={styles.button1} color="warning" onPress={() => {      let my = this;      this.showToast(true);      setTimeout(function () { my.showToast(false) }, 1000);      this.saveItemCart();      this.hideModalEdit(false);      }}>Save</Button>

The problem is in the input of the EDIT cart modal(i.e. page). If the user puts the comment initially before adding it to his cart, then when I open the edit it has the correct comment. If I change it and click save, it does not work.

Reduce Memory Usage in React Native iOS App

$
0
0

My app works perfectly fine in iphone7 , iphone 11 (real devices) , but crashes as soon as it navigates to another page in iphone6 and iphone XR. The error which i get from bugsnag is

Out Of Memoryunknown method, The app was likely terminated by the operating system while in the foreground

After going through the profile for memory leaks in Xcode i figured out 2 processes :

1.VM: ImageIO_PNG_Data was taking too much memory ~ 400 MiB

2.VM :CoreAnimation was taking too much memory. ~ 700 MiB

For image , i just resolved to lower quality images and the memory usage decreased, but in case of CoreAnimation does anyone have any idea how to lower the value in React-Native? Any suggestion would help. I've used react-navigation for navigating from one page to another.

Please check below image for your reference:

Do ask if any more information is required.

Please check below image for your reference

React native Branch io deep linking in IOS not working

$
0
0

I have followed the set up doc of branch for react native io i.e. https://help.branch.io/developers-hub/docs/react-native

React native Branch io deep linking is working fine for Android part and For ios part if click the banner from my website it is taking me to appstore and not the app though app is installed in device.

When copy the link getting created when user clicking on the banner and pasting it in notepad and on long press I am getting "open in your app" option and its navigating to app.

Can't compile React Native iOS app to run on physical device, issue with React Native Firebase

$
0
0

For some reason since recently, I cannot run my React Native app on a physical device from Xcode or even from the command line. I'm getting the following error:

duplicate symbol '_md5_block_data_order' in:    /XXX/Library/Developer/Xcode/DerivedData/XXXX-bdrylwsxpcqgzvgkcljteyttcdmr/Build/Products/Debug-iphoneos/BoringSSL-GRPC/libBoringSSL-GRPC.a(md5.o)    /XXX/project/ios/Pods/OpenSSL-Universal/ios/lib/libcrypto.a(md5_dgst.o)ld: 1 duplicate symbol for architecture arm64clang: error: linker command failed with exit code 1 (use -v to see invocation)

However it works fine from a simulator. And I can upload the app to AppStoreConnect without any issue.

From what I understand it looks like the same symbol exists in 2 libraries. Not sure why, most likely one of the mobile app dependencies.

In the list of Pods installed I have both BoringSSL-GRPC (0.0.3) and OpenSSL-Universal (1.0.2.19)

BoringSSL is used by Firebase and OpenSSL is used by Flipper.

This is the list of third party dependencies I use:

  pod 'Firebase/Core', '~> 6.3.0'  pod 'Firebase/Messaging', '~> 6.3.0'  pod 'Firebase/Firestore', '~> 6.3.0'  pod 'Firebase/Auth', '~> 6.3.0'  pod 'TrustKit'  pod 'Stripe', '16.0.0'  pod 'Amplitude-iOS', '~> 4.5'  pod 'Intercom', '~> 5.5.1'  flipper_pods()

When I remove Firebase all together, it works fine and I can run my app on the device. But I need Firebase...

Any idea how to resolve this?

Thanks!


React Native: Determine number of lines of Text component

$
0
0

As the title says, I've been trying to find a way to determine the number of lines the text component AFTER it has been given text. Look at my example below.

<Text>    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi semper ut ipsum in ultrices. Vivamus fringilla lacinia odio in accumsan. Proin sit amet pellentesque tortor. Nam mollis sit amet ligula id convallis. Etiam in semper diam. Cras id elit consectetur, interdum ante id, tincidunt nisi. Integer non elit placerat, dignissim nibh at, faucibus sem. Curabitur nec posuere turpis. Vivamus rhoncus nulla vitae mi imperdiet, elementum eleifend mi laoreet. Vestibulum molestie turpis non nibh elementum, sed ornare magna tristique. Aliquam erat volutpat. Phasellus volutpat mi vel tempor finibus.</Text>

At runtime, how can I determine how many lines this Text component has rendered. This number will vary depending on device (eg. iPhone 5 will need to render more lines vs iPhone 6+ as it has a smaller screen size). I've checked the source code for the Text component but there doesn't seem to be anything I'm looking for.

I am using React Native 0.24.

Any ideas?

Cheers.

Can not getProducts iOS simulator react-native-iap

$
0
0

I am trying to get some products details configured on app store connect (saved but not submited)

react-native-iap: 4.4.3

react-native: 0.62.0

I am running this code on iOS simulator

import * as InAppPurchases from 'react-native-iap';InAppPurchases.initConnection().then( canMakePayments => {    console.log(canMakePayments);    return InAppPurchases.getProducts(['com.xxx.xxx.abo'])}).then(result => {    console.log(result);}).catch(err => {    console.log(err);})

canMakePayments is true

but getProducts catch with [Error: An SSL error has occurred and a secure connection to the server cannot be made.]

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?

How to update the app version in react native ios app?

$
0
0

How can I change the apple app version which is build using react native.

I got this email from apple app store -

Dear Developer,

We identified one or more issues with a recent delivery for your app, "APP_NAME" 1.0 (1.0.2). Please correct the following issues, then upload again.

ITMS-90062: This bundle is invalid - The value for key CFBundleShortVersionString [1.0] in the Info.plist file must contain a higher version than that of the previously approved version [1.1]. Please find more information about CFBundleShortVersionString at https://developer.apple.com/documentation/bundleresources/information_property_list/cfbundleshortversionstring

Best regards,

The App Store Team

Cannot see all devices with Bluetooth (not interested in establish connections)

$
0
0

I would like clarification on device scanning using bluetooth in React Native. I state one thing: I am not interested in establishing connections with the devices, it is enough for me to know that they are present. I am using react-native-ble-plx library and I have tried it both on Android devices (Samsung J5 and Huawei P8) and on iOS devices (two iPhone 8 and one iPad) but also on laptops (Lenovo Thinkpad and two MacBook Pro) plus various non-personal devices (Smart TV, home speakers, smart watch and so on.

I noticed that not all devices are capable of scanning each other. I am using the startDeviceScan function, for example with the Samsung J5 I can see all the IoT devices and all the iOS devices but I cannot see the Huawei. Worse still, with iPhones I can see all IoT devices, but I can't see any of the Android smartphones.

What are the causes? What can I do to solve this problem (if it were possible)? Are there other libraries that would allow me to see the signal from other devices using React Native?

React Native api calls don't occur outside Remote Debug mode (iOS only)

$
0
0

I am having a strange issue, the app (iOS and Android) works fine when being used in a Simulator under Remote Debug mode.

However, when I turn the Remote Debug mode off for iOS development, I am unable to receive data back from the server. This is not the case with Android it works fine as expected outside Remote Debug mode.

Wonder what might the case with iOS when I turn the Remote Debug mode off?

I have also attached a screenshot of Network requests from iOS simulator if it is helpful in narrowing down the issue here.

iOS Screenshot

Imagepicker React Native crashes on iOS but works fine on Android

$
0
0

I am currently using imagepicker on react native. When I use android to pick image it works fine. However when I use iOS it crashes when I choose a photo.

This is the error it shows in xcode debugger:

2020-04-03 11:54:27.802434+0800 app[7218:1993193] -[NSURLResponse allHeaderFields]: unrecognized selector sent to instance 0x28281aba0 2020-04-03 11:54:27.802766+0800 app[7218:1993193] * Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[NSURLResponse allHeaderFields]: unrecognized selector sent to instance 0x28281aba0' * First throw call stack: (0x19d01c164 0x19cd30c1c 0x19cf1a7e0 0x19d02085c 0x19d022b60 0x102b27bc8 0x102b27a90 0x102b01ce0 0x1059f5d10 0x1059f718c 0x1059fe968 0x1059ff580 0x105a0b0f0 0x19cd23714 0x19cd299c8) libc++abi.dylib: terminating with uncaught exception of type NSException

and this is my code:

chooseImage = async (id) => {        //await this.askPermissionsAsync();        let options = {          title: 'Select Image',          storageOptions: {            skipBackup: true,            path: 'images',          },        };        ImagePicker.showImagePicker(options, (response) => {          console.log('Response = ', response.error);          if (response.didCancel) {            console.log('User cancelled image picker');          } else if (response.error) {            console.log('ImagePicker Error: ', response.error);          } else {            const source = { uri: response.uri };            // You can also display the image using data:            // const source = { uri: 'data:image/jpeg;base64,'+ response.data };            // alert(JSON.stringify(response));            let file_data = [...this.state.fileData];            file_data[id] = response.data;            let file_uri = [...this.state.fileUri];            file_uri[id] = response.uri;            this.setState({filePath:response, fileData: file_data, fileUri: file_uri});          }        });      }

I have also added the permissions in info.plist:

<key>NSCameraUsageDescription</key><string></string><key>NSPhotoLibraryUsageDescription</key><string></string><key>NSPhotoLibraryAddUsageDescription</key><string></string><key>NSDocumentsFolderUsageDescription</key><string></string>

but the problem still persist in ios.


Continuously increasing counter with long press React Native

$
0
0

I have a button next to a TextInput that increases its counter when pressed.

<TouchableWithoutFeedback onPress={() => {this.increaseAmount(step, rowID)}}><View style={styles.amountPlusButtonContainer}><Text style={styles.amountButtonText}>+</Text></View></TouchableWithoutFeedback>

It currently increases by 1 each time I tap the button. What I want to achieve is to keep increasing the counter for as long as the user is pressing it.

I have tried to use setInterval() but I don't know exactly when to stop it nor if it's the right approach to this problem.

React Native Responsive Font Size

$
0
0

I would like to ask how react native handle or do the responsive font. For example in iphone 4s i Have fontSize: 14, while in iphone 6 I have fontSize: 18.

BatchedBridge error in React Native on iOS

$
0
0

I have a simple native iOS app that I want to integrate React Native into. When I open the view controller, I get an error:

> Error calling RCTLog.logIfNoNativeHook> > Unhandled JS Exception: Could not get BatchedBridge, make sure your> bundle is packaged correctly> > RCTFatal> -[RCTCxxBridge handleError:]> __34-[RCTCxxBridge _initializeBridge:]_block_invoke facebook::react::RCTMessageThread::tryFunc(std::__1::function<void ()>> const&)> facebook::react::RCTMessageThread::runOnQueue(std::__1::function<void> ()>&&)::$_1::operator()() const void> std::__1::__invoke_void_return_wrapper<void>::__call<facebook::react::RCTMessageThread::runOnQueue(std::__1::function<void> ()>&&)::$_1&>(facebook::react::RCTMessageThread::runOnQueue(std::__1::function<void> ()>&&)::$_1&&&)> std::__1::__function::__func<facebook::react::RCTMessageThread::runOnQueue(std::__1::function<void> ()>&&)::$_1,> std::__1::allocator<facebook::react::RCTMessageThread::runOnQueue(std::__1::function<void> ()>&&)::$_1>, void ()>::operator()() std::__1::function<void> ()>::operator()() const invocation function for block in> facebook::react::RCTMessageThread::runAsync(std::__1::function<void> ()>)> __CFRUNLOOP_IS_CALLING_OUT_TO_A_BLOCK__> __CFRunLoopDoBlocks> __CFRunLoopRun CFRunLoopRunSpecific> +[RCTCxxBridge runRunLoop]> __NSThread__start__> _pthread_body> _pthread_body thread_start

This is my Podfile:

# Uncomment the next line to define a global platform for your project# platform :ios, '9.0'target 'NativeRNTest' do  # Comment the next line if you're not using Swift and don't want to use dynamic frameworks  use_frameworks!  pod 'React', :path => '../node_modules/react-native', :subspecs => ['Core','CxxBridge', # Include this for RN >= 0.47'DevSupport', # Include this to enable In-App Devmenu if RN >= 0.43'RCTText','RCTNetwork','RCTWebSocket', # needed for debugging'BatchedBridge',    # Add any other subspecs you want to use in your project  ]  # Explicitly include Yoga if you are using RN >= 0.42.0  pod "yoga", :path => "../node_modules/react-native/ReactCommon/yoga"  # Third party deps podspec link  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'  # Pods for NativeRNTest  target 'NativeRNTestTests' do    inherit! :search_paths    # Pods for testing  end  target 'NativeRNTestUITests' do    inherit! :search_paths    # Pods for testing  endend

My environment:

>react-native infoScanning folders for symlinks in /Users/[redacted]/Projects/native_rn_demo/node_modules (5ms)Environment:  OS: macOS Sierra 10.12.6  Node: 8.9.0  Yarn: 1.1.0  npm: 5.6.0  Watchman: 4.9.0  Xcode: Xcode 9.2 Build version 9C40b  Android Studio: 2.3 AI-162.4069837Packages: (wanted => installed)  react: ^16.0.0 => 16.0.0  react-native: ^0.51.0 => 0.51.0

I've searched for this problem, and all the solutions are for Android, and don't seem to work here. Any ideas?

Pod install not working in react-native mac os catalina 10.15

$
0
0

Error: System/Library/Frameworks/Ruby.framework/Versions/2.3/usr/bin/ruby: bad interpreter: No such file or directory

in mac os catalina

iOS - Expo Notifications.getExpoPushTokenAsync() not getting token

$
0
0

I'm trying to receive a push notification token from my app, but I never get a token. I tried debugging using a few alerts, and I can see that I get "granted" returned when accepting notifications. I have only tested for iOS.

i'm running

"expo": "^32.0.0","react-native": "https://github.com/expo/react-native/archive/sdk-32.0.0.tar.gz",

I tried using the guide from https://docs.expo.io/versions/latest/guides/push-notifications/

Since it didn't work i tried the snack they provided from the API reference: https://docs.expo.io/versions/v32.0.0/sdk/notifications/

snack: https://snack.expo.io/@documentation/pushnotifications

This is my current code:

 static registerForPushNotificationsAsync = async kid => {    if (Constants.isDevice) {      const { status: existingStatus } = await Permissions.getAsync(        Permissions.NOTIFICATIONS      );      let finalStatus = existingStatus;      if (existingStatus !== "granted") {        const { status } = await Permissions.askAsync(          Permissions.NOTIFICATIONS        );        finalStatus = status;      }      if (finalStatus !== "granted") {        alert("Failed to get push token for push notification!");        return;      }      let token = await Notifications.getExpoPushTokenAsync();      alert("finalstatus "+ finalStatus);      alert("existing status "+ existingStatus);      alert(token);      // POST the token to your backend server from where you can retrieve it to send push notifications.      return await fetch(`${Api.APIEndpoint}/app/notification`, {        method: "POST",        headers: {          Accept: "application/json","Content-Type": "application/json"        },        body: JSON.stringify({          token: token,          kid: kid        })      });    } else {      alert("Must use physical device for Push Notifications");    }  };

the first two alerts triggers as expected (and returns "granted" when I accept), but alert(token) seems to be empty.

I also noticed that I get asked for two permissions. First it asks for permission to use notifications and then it asks for access to photos. I don't need permissison to photos and I am curious why it asks for that.

As far as I have understood reading the documentation, FCM is required only for android devices? I will need it to work on android as well, but I figured making it work for one platform first and then move on.

I installed the app on my iPhones using Testflight. Does the token only "appear" once the app is approved for the app store?

Maybe there's something else i missed in the documentation.

Any help or point in the right direction will be much appreciated.

Viewing all 16907 articles
Browse latest View live


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