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

react-native: deep linking not working when server returns 302

$
0
0

I'm writing a react native app that is super simple: it have 2 screens.

import { authorize } from 'react-native-app-auth';class HomeScreen extends Component {  _handleOpenURL() {    console.log('_handleOpenURL 1');  }  componentDidMount() {    authorize(config);  }  render() {    return (<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}><Text>Home Screen</Text></View>    );  }class LoginScreen extends Component {  _handleOpenURL() {    console.log('_handleOpenURL');  }  componentDidMount() {    Linking.addEventListener('url', this._handleOpenURL);  }  render() {    return (<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}><Text>Login Screen</Text>       </View>    );  }}const AppNavigator = createSwitchNavigator(  {    Home: {       screen: HomeScreen     },    Login: {      screen: LoginScreen,      path: 'login'    }  });const prefix = 'myapp://'const App = createAppContainer(AppNavigator);const MainApp = () => <App uriPrefix={prefix} />;export default MainApp;

My idea is to call authorize()(this function is a promise that returns a 302 with a deep linking like myapp://login/?login_challenge=007728866a60408a85c711aebe346574) and it should open LoginScreen.

My problem: when authorize() is called, it opens and close a view and HomeScreen is displayed.

If I try to open same url from browser, it works.

What can I do to solve it?


problems library react-native-contacts not working ios

$
0
0

I was testing an example from the react-native-contacts library in which I leave the link: https://github.com/morenoh149/react-native-contacts/tree/master/example

at the moment of running the example, a view is displayed with the supposed contacts that I have stored in ios but nothing can be displayed.

my problem is that I don't know what can be missing in the example from the same library, in android it works perfect. But the problem is ios in which it is not working.

please help.

react-native-contacts image example

'expo' is not recognized as an internal or external command

$
0
0

After running npm install -g expo-cli and successfully installing the packages globally, expo is still not recognized as an internal or external command. Does anyone know how I might get around this issue using windows 10, or what to do in terms of something like a path variable.

How to make PERMISSIONS.IOS.MEDIA_LIBRARY available in IOS simulator?

$
0
0

I develop apps with RN v0.61.5. I run in iOS simulator iPhone 11 (13.4.1). I working with device permission. I use react-native-permission v2.1.4 (here the repo). Based on their documentation, for check and request to media library in iOS, I have to use PERMISSIONS.IOS.MEDIA_LIBRARY. Also, this is what MEDIA_LIBRARY is based on apple developer doc. But, when I check with checkAPI like:

const result = await check(PERMISSIONS.IOS.MEDIA_LIBRARY)

it return unavailable. I haven't check this in real device since I do not have one. Is it only available in real device or is there any way to make it available in iOS simulator? So I can do testing with simulator only. Thanks.

Unable to resolve module 'react-navigation' from .../App.js: Module 'react-navigation' does not exist in the Haste module map

$
0
0

So I've just set up an app to start building it out and I keep getting this error from my App.js. This is a part of a udemy course in which I've followed every instruction to a T...so im beyond confused of what the hell is happening and I've followed every suggestion I can find. Unable to resolve module react-navigation from /Users/3x7r3m157/Development/React-Native/food/App.js: Module react-navigation does not exist in the Haste module map

This might be related to https://github.com/facebook/react-native/issues/4968To resolve try the following:  1. Clear watchman watches: `watchman watch-del-all`.  2. Delete the `node_modules` folder: `rm -rf node_modules && npm install`.  3. Reset Metro Bundler cache: `rm -rf /tmp/metro-bundler-cache-*` or `npm start -- --reset-cache`.  4. Remove haste cache: `rm -rf /tmp/haste-map-react-native-packager-*`.facebook::ReactABI35_0_0::JSIExecutor::defaultTimeoutInvoker(std::__1::function<void ()> const&, std::__1::function<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > ()>)facebook::ReactABI35_0_0::JSIExecutor::defaultTimeoutInvoker(std::__1::function<void ()> const&, std::__1::function<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > ()>)ED0789CD-8D80-39F4-9651-D8707D9C0337ED0789CD-8D80-39F4-9651-D8707D9C0337_dispatch_main_queue_callback_4CF97285ACB-7B21-393A-ABF6-03F1DBB5D2A297285ACB-7B21-393A-ABF6-03F1DBB5D2A2CFRunLoopRunSpecificGSEventRunModalUIApplicationMainExponent0DC9A4BA-C3E8-3487-99DB-1B5C86597AF5

Heres my App.js:

import { createAppContainer } from 'react-navigation';import { createStackNavigator } from 'react-navigation-stack';import SearchScreen from './src/screens/SearchScreen';const navigator = createStackNavigator ({  Search: SearchScreen}, {  initialRouteName: 'Search',  defaultNavigationOptions: {    title: 'BusinessSearch'  }});export default createAppContainer(navigator);

React Native offline App using react-native-sqlite-storage

$
0
0

I am new to react native. I want to build an offline react native app for storing user data (Basic user details, user personal documents, images, etc). I already gone through some documents about react-native-sqlite-storage and I would like to integrate it. But not sure,

  1. If I can recover all the user data when user delete application data
  2. What is advantage of using react-native-sqlite-storage than redux-persist for offline app development?

Add Review Information screenshots in apple store?

$
0
0

I'm trying to add in-app purchase in my ios App "react native".But in App store should i add screenshots in Review Information sections, So what's should i add here?shot

and I use 'react-native-iap',

when I call getProducts() it returns empty array so how can i fix it?

Xcode Build Failing due to "bundle format unrecognized, invalid, or unsuitable"

$
0
0

I have a dilemma in regards to not being able to run a React Native project in Xcode because of an error that I have spent days trying to resolve.

I have attached a screenshot of the error screenshot of build error in Xcode

It is stating that:

"/Users/diamoniquedanner/Library/Developer/Xcode/DerivedData/Entrepreneur-elimewlshojayqdyaklhiziodxbi/Build/Products/Debug-iphoneos/Entrepreneur.app: bundle format unrecognized, invalid, or unsuitable Command /usr/bin/codesign failed with exit code 1"

I would like to state that this project was handed to me by a client and I have tried creating anew provisioning profile, create a new certificate, etc. (however I may be doing it wrong) and I cannot contact the old team for any resources.

Best regards,Dia'Monique


Test IAP in simulator - react-native?

$
0
0

I use react-native-iap, And I have Non-Consumable so i use getAvailablePurchases() but in every time i getting this error

Cannot connect to iTunes Store

So i can't test what i do or if the user buying successfully or not!

So is there a way to solve this issue?

Code

export default class PurchaseScreen extends Component {  componentDidMount() {    this.getPurchases();  }  getPurchases = async () => {    try {      const init = await RNIap.initConnection();      console.log('init?', init);      const availablePurchases = await RNIap.getAvailablePurchases(items);      console.log('availablePurchases', availablePurchases);    } catch (err) {      console.warn(err);    }  };subscribe = ()=>{    ...}  render() {    return (<TouchableOpacity onPress={()=>this.subscribe()} style={styles.btn}><Text style={styles.lable}>Subscrib</Text></TouchableOpacity>   )  }}

ld: library not found for -lCocoaAsyncSocket

$
0
0

I'm using App Center to manage the build for iOS and the following is error I'm receiving in the build output:

    ld: library not found for -lCocoaAsyncSocketclang: error: linker command failed with exit code 1 (use -v to see invocation)** ARCHIVE FAILED **##[error]Error: /usr/bin/xcodebuild failed with return code: 65

I ran the build in Xcode and the archive was successful.

Any thoughts on why this fails in App Center ?

What is next technology for mobile developer after learn React Native? Flutter or Native? [closed]

$
0
0

I have experience with React Native to build Cross Platform and working with it. But about perform and UI I think Flutter is better than React Native because React Native depend so much for Native. So my question If I want to go further with Mobile Application I should comeback to learn Native(iOS) or Flutter?

How can I make two phones running the same app communicate through bluetooth

$
0
0

I would like to build an app in which a smartphone(using any OS) can discover other smartphones in the surroundings using Bluetooth. I know this can be probably achieved using BLE.However, I would like to a communication, in which the devices can "ping" each other through Bluetooth by pressing a button within the app. The app should display something on both devices(think an image) for a few seconds if the button in both devices is pressed at the same time. For this, I assume BLE is not enough as it does not support communication between two smartphones and the BLE central and peripheral model does not seem to fit my aim.I'm new to app development and while I found multiple questions on this, they are pretty old. Please give me pointers to libraries/resources which would help me achieve this.

React Native Push Notifications not appearing in settings

$
0
0

I am new to react native and I am trying to set up push notifications via iOS.

I have installed pushNotificationios and followed the instructions given. I have also signed up as an Apple Developer.

When I run my app the push notifications don't seem to work. When I go into my iPhone settings and click on the app it does not display notifications.

settings

Here is my code

import PushNotificationIOS from '@react-native-community/push-notification-ios';import PushNotification from "react-native-push-notification";const configure = () => { PushNotification.configure({   onRegister: (token) => {    console.log('TOKEN:', token);     //process token   },   onNotification: (notification) => {     // process the notification     console.log("NOTIFICATION:", notification);     // required on iOS only     notification.finish(PushNotificationIOS.FetchResult.NoData);   },   permissions: {     alert: true,     badge: true,     sound: true   },   popInitialNotification: true,   requestPermissions: true, });}; export {    configure,   };

Is it possible to do multiple app builds concurrently in React Native?

$
0
0

I was wondering if it's possible to have different apps being built out of a single repo in React Native. The reason I'm trying to do this would probably be a huge edge case, but it's basically for unit testing RN modules that I'm developing.

I know I can unit test individual components using Enzyme, but I have some modules that are part of a whole framework, and I need to do end-to-end unit tests on them. So my thinking is that I should build the app and run unit tests on it with Appium. But what if there are multiple unit tests? I guess we would need to build multiple separate apps? But there's only one index.js file.

I was reading that I could set up some app targets and schemes (iOS) and equivalent stuff in Android. But how would I handle that on the RN side? Where can I specify which .js file is the entry point for each target? And how does RN handle building different targets?

https://www.dev6.com/frameworks/building-multiple-apps-from-one-react-native-project/Read this article about setting up multiple schemes and using those to set environment variables that could influence control flow in the app. However, this would mean that I would have to run the unit tests in serial, loading the same app up over and over with different env (not the end of the world, I guess).

I was thinking that if I had multiple index.js files, one for each unit test, I could maybe set up some separate app targets/schemes and use those, but I guess I would have to figure out how to build and run them concurrently for concurrent unit testing. I think that the react-native run-ios and run-android commands just build a single app though, so I'm not sure how I'd fit that into my unit testing workflow.

Any thoughts on this strategy or other possible strategies would be very welcome! Thanks :)

Unable to validate the fields into React-native

$
0
0

I'm working into functional components and managing the sate by hooks but facing problem into hooks while validation the form.

here is my states:

const [email, setEmail] = useState('');const [password, setPassword] = useState('');const [validEmail, setValidEmail] = useState(true);const [validPassword, setValidPassword] = useState(true);

and here is my validation method is working fine into debug app but facing problem when I released the app.

const validateFields = (): void => {const emailText = emailconst validEmailText = validEmailconst passwordText = passwordconst validPasswordText = validPasswordif (!validEmailText || !emailText) {  setValidEmail(false);  return;} else if (!validPasswordText || !passwordText) {  setValidPassword(false);  return;}setIsLoading(true);doSingIn(email, password);

};


React-Native Memory leak, possibly from redux, please see details

$
0
0

So I'm building a react-native application for my work, and I'm using redux and websockets. I'm experienced a bad memory leak when i go to the messenger screen repeatedly, which i suspect has something to do with redux actions / state changes being stored in memory. I have a pretty nested store object that is being modified when chat messages load/ a new message comes in. The leak is especially bad in debug mode, but improves significantly in production but the memory still climbs over time. Could someone take a look at my reducer and tell me if the way im modified nested properties in an array may be causing this and if there is any alternative? I'm also using "store.getState()" and store.dispatch() in the socket because it is not a react component so i have no other means of getting things like the auth token since there are no props.

I'm using a lot of .find() and .map() methods to modify my nested redux state (adding messages to a chat room) and im wondering if these objects are being stored in memory every time i trigger these functions. Any help would be much appreciated!Thank you

Here is my reducer:

const chatReducer = (state = {rooms: [], selectedChat: ''}, action) => {  switch (action.type) {    case 'LOAD_CHATS':      return {...state, rooms: [...state.rooms, ...action.rooms]};    case 'LOAD_MESSAGES':      const newRooms = state.rooms.map(room => {        if (room.id === state.selectedChat) {          room.messages = action.messages;        }        return room;      });      return {...state, rooms: newRooms};    case 'NEW_MESSAGE':      const newMessages = state.rooms.map(room => {        if (room.id === action.item.room) {          return {            ...room,            messages: [              ...room.messages,              {                user: action.item.user,                date: action.item.date,                message: action.item.msg,              },            ],          };        }        return room;      });      return {...state, rooms: newMessages};    case 'SELECTED_CHAT':      return {...state, selectedChat: action.id};    case 'SYNC_MESSAGES':      const roomById = state.rooms.find(room => room.id === action.id);      const syncedMessages = action.msgs.map(msg => {        if (!roomById.messages.find(el => el.id === msg.id)) {          return msg.messages;        }      });      const roomMessages = state.rooms.map(room => {        if (room.id === action.id) {          return {            ...room,            messages: [...room.messages, ...syncedMessages],          };        }        return room;      });      return {...state, rooms: roomMessages};    default:      return state;  }};export default chatReducer;

and here is my socket utilities file:

import io from 'socket.io-client';import {store} from '../redux/store';let socket = null;const getSocket = () => {  return socket;};const init = () => {  const token = store.getState().auth.token;  socket = io.connect('********************',    {      query: {token},      transports: ['websocket'],    },  );};const handleConnect = data => {  socket.on('connecting', () => {    console.log('Socket connecting...');  });  socket.on('connect', x => {    console.log('CONNECTED', x);    socket.emit('RegisterUser', {      User: data.username,      Client: data.client,      System: 'Mobile',    });  });  socket.on('ChatMessages', msgs => {    store.dispatch({type: 'LOAD_MESSAGES', messages: msgs[0].messages});  });  socket.on('UserTypeing', msg => {    store.dispatch({type: 'USER_TYPING', data: msg});  });  socket.on('UserTypeingStopped', msg => {    store.dispatch({type: 'STOPPED_TYPING', user: msg});  });  socket.on('NewMessage', msg => {    store.dispatch({type: 'NEW_MESSAGE', item: msg});  });  socket.on('SortedMessages', msgs => {    const id = store.getState().chat.selectedChat;    store.dispatch({type: 'SYNC_MESSAGES', msgs: msgs.resources, id});  });  socket.on('connect_failed', msg => {    console.log(msg, 'CONNECT FAILED');  });  socket.on('connect_error', msg => {    console.log(msg, 'Connect Error!');  });  socket.on('connect_timeout', msg => {    console.log(msg, 'timeout!');  });  socket.on('error', msg => {    console.log(msg, 'Error!');  });  socket.on('reconnect', attemptNumber => {    console.log('recon attempt:', attemptNumber);  });};const getRooms = () => {  socket.on('GetChatRooms', rooms => {    const arr = [];    rooms.forEach(room => {      if (!store.getState().chat.rooms.find(el => el.id === room.id)) {        arr.push(room);      }    });    if (arr.length) {      store.dispatch({type: 'LOAD_CHATS', rooms: arr});    }  });};const getRoomMessages = id => {  console.log('GETROOMMESSAGES');  socket.emit('GetChatMessages', id);};const userUpdate = () => {  socket.on('userupdate', data => {});};const handleDisconnect = () => {  socket.on('disconnect', () => {    console.log('DISCONNECTED');  });};const startTyping = roomId => {  socket.emit('SendRoomImTyping', {room: roomId});};const stopTyping = roomId => {  socket.emit('SendRoomStopTyping', {room: roomId});};const sendRoomMessage = (roomId, message) => {  socket.emit('SendRoomMessage', {room: roomId, message});};const updateRoomMessages = (id, start) => {  console.log(id, start);  socket.emit('GetChatMessagesFiltered', {id, start});};const disconnect = () => {  socket.disconnect();};const SocketTools = {  init,  handleConnect,  getRooms,  getRoomMessages,  updateRoomMessages,  userUpdate,  disconnect,  handleDisconnect,  getSocket,  sendRoomMessage,  startTyping,  stopTyping,};export default SocketTools;

React-Native iOS Launch Options not received by Native Module

$
0
0

When the app is launched by opening a notification, the launchOptions given by iOS to the function didFinishLaunchingWithOptions does have the notification object but that dictionary never gets passed around to the native module through RCTBridge. Is there a way to get the launchOptions in the native module? or am I missing something here?

My AppDelegate didFinishLaunchingWithOptions

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {    [FIRApp configure];    [FIRMessaging messaging].delegate = self;    NSURL *jsCodeLocation;    jsCodeLocation = [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index" fallbackResource:nil];    RCTRootView *rootView = [[RCTRootView alloc] initWithBundleURL:jsCodeLocation                                                        moduleName:@"myModuleName"                                                 initialProperties:nil                                                     launchOptions:launchOptions];    rootView.backgroundColor = [[UIColor alloc] initWithRed:1.0f green:1.0f blue:1.0f alpha:1];    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];    UIViewController *rootViewController = [UIViewController new];    rootViewController.view = rootView;    self.window.rootViewController = rootViewController;    [self.window makeKeyAndVisible];    return YES;}

Code in my Module in Swift to get launchOptions

// launchOptions is always nillet notification: Any = self.bridge.launchOptions?[UIApplication.LaunchOptionsKey.remoteNotification] as Any;

react native iOS - JSON VALUE '' of type nsnull cannot be converted to a valid url

$
0
0

Each time I register to the app via expo after I insert the new mail and the password I get this screen.this is the screen error

even after I close the expo end open again it show the same red screen with message.But if I close the project (refresh it by shake) and enter the whole project again, now with an exist user it and works perfectly so far...(still got fixes to do).


This is the **Register.js page code:**

import React, { Component } from "react";import { View, Button, StyleSheet, TextInput, Alert, AsyncStorage } from "react-native";const URL = 'http://185.60.170.14/plesk-site-preview/ruppinmobile.ac.il/site17/WebService.asmx';export default class Register extends Component {  state = {    email: "",    password: "",    repassword: ""  };  Register = () => {    if(this.state.password != this.state.repassword){      Alert.alert("Error",'Password does not match',        [{ text: "OK", onPress: () => null }],        { cancelable: false }      );      this.setState({password: '', repassword: ''});      return;    }    let data = {      email: this.state.email,      password: this.state.password    };    fetch(URL +"/Register", {      // בקשהלשרתלמתודה Register      body: JSON.stringify(data), // שליחתפרמטרים      method: "POST",      headers: {"Content-type": "application/json; charset=UTF-8"      }    })      .then(res => {        return res.json();      })      .then(userData => {        console.log(userData.d);        if (userData.d == "Error: This email is already in use") {          Alert.alert("Error",            userData.d,            [{ text: "OK", onPress: () => null }],            { cancelable: false }          );        } else {          AsyncStorage.setItem("@KnowingFriends:user", userData.d);          this.props.navigation.navigate("MainApp");        }      })      .catch(err => {        console.error(err);      });  };  render() {    return (<View style={styles.container}><TextInput          style={styles.input}          onChangeText={text => this.setState({ email: text })}          value={this.state.email}          placeholder="Email"        /><TextInput          style={styles.input}          onChangeText={text => this.setState({ password: text })}          value={this.state.password}          secureTextEntry={true}          placeholder="Password"        /><TextInput          style={styles.input}          onChangeText={text => this.setState({ repassword: text })}          value={this.state.repassword}          secureTextEntry={true}          placeholder="Repeat Password"        /><Button onPress={this.Register} title="Submit" color="#841584" /><Button          onPress={() => {            this.props.navigation.navigate("Login");          }}          title="Go back"          color="#841584"        /></View>    );  }}const styles = StyleSheet.create({  container: {    flex: 1,    backgroundColor: "#fff",    alignItems: "center",    justifyContent: "center"  },  input: {    height: 40,    width: 300,    borderColor: "gray",    borderWidth: 1  }});

how can I fix this issue ?

React Native scroll view not showing

$
0
0

I have a scroll view at the top level of the view hierarchy. I'm trying to get it to show its content but I haven't had any luck.

I see that the documentation says scroll views need a bounded height to work. I can't seem to get it to have a bounded height. This is what I have so far.

'use strict';const React = require('react-native');const {  StyleSheet,  Text,  View,  BackAndroid,  TextInput,  TouchableNativeFeedback,  ScrollView} = React;const ActionButton = require('./action-button'),    Dimensions = require('Dimensions');module.exports = React.createClass({  handleBackButtonPress () {    if (this.props.navigator) {      this.props.navigator.pop();      return true;    }    return false;  },  componentWillMount () {    BackAndroid.addEventListener('hardwareBackPress', this.handleBackButtonPress);  },  componentWillUnmount () {    BackAndroid.removeEventListener('hardwareBackPress', this.handleBackButtonPress);  },  onInputFocus (refName) {    setTimeout(() => {      let scrollResponder = this.refs.getScrollResponder();      scrollResponder.scrollNativeHandleToKeyboard(        React.findNodeHandle(this.refs[refName]),        110,        true      );    }, 50);  },  render: function() {    return (<View style={styles.scrollWrapper}><ScrollView ref='scrollView' style={styles.scroller}><View style={styles.container}><View style={styles.header}><Text>New Post</Text><View style={styles.actions}><ActionButton handler={this.handleBackButtonPress} icon={'fontawesome|close'}                    size={15} width={15} height={15} /></View></View><View style={styles.content}><TextInput underlineColorAndroid={'white'}                placeholder={'Who\'s your professor?'}                ref='professor'                onFocus={this.onInputFocus.bind(this, 'professor')}                /><TextInput multiline={true}                underlineColorAndroid={'white'}                placeholder={'What do you think?'}                ref='post'                onFocus={this.onInputFocus.bind(this, 'post')}                /></View><View style={styles.footer}><TouchableNativeFeedback                background={TouchableNativeFeedback.SelectableBackground()}><View style={{width: 50, height: 25, backgroundColor: 'green'}}><Text>Submit</Text></View></TouchableNativeFeedback></View></View></ScrollView></View>    );  }});const styles = StyleSheet.create({  scrollWrapper: {    flex: 1  },  scroller: {    flex: 1  },  container: {    flex: 1,    flexDirection: 'column',    justifyContent: 'flex-start',    backgroundColor: 'white',    padding: 5,  },  post: {    flex: 1,  },  actions: {    flex: 1,    flexDirection: 'row',    justifyContent: 'flex-end',    alignSelf: 'center'  },  header: {    flex: 1,    position: 'absolute',    top: 0,    left: 0,    right: 0,    height: 35,    padding: 5,    flexDirection: 'row'  },  content: {    flex: 1,    position: 'absolute',    top: 35  },  footer: {    flex: 1,    position: 'absolute',    bottom: 0,    left: 0,    right: 0,    height: 35  }});

EDIT: So I changed the background colors of all the components to something obvious. I was able to simplify the view, so now the ScrollView is the root of the component. The container view (the immediate child of the ScrollView) is the one who isn't filling all the available space. I'm still playing around with it but any help is much appreciated.

Can't extract cities of country OpenWeather

$
0
0

I wanna use open-weather API for my application. for that i thought i might be able to save cities and their IDs in my own app in a json file and whenever i user wants a locations weather, app selects city's ID from json and make API call.

for that i downloaded a 30MB Json file provided by Openweather, it contains all countries and all theirs cities. putting a 30MB in my app isn't a good idea apparently. so i decided to extract my country cities only. but the point is, this idea could not be done. so many cities from different countries has same names. and extracted json was huge again. even some coutry codes are cities in other countries.

i wonder if there is a way better implementation. or any idea or way to extract just cities of a country.

any help to implement weather call in my app for different cities would be appreciated

Viewing all 16562 articles
Browse latest View live


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