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

React Native - Issue with loading images IOS/Xcode -load failed with error Error Domain=NSURLErrorDomain Code=-999 "cancelled"

$
0
0

There is a page on my app which has cards with some small pictures on.

The apps works perfectly fine on android.

However in Xcode/iOS I am getting the following errors for each picture:

"LocalDataTask <4D2BF55D-B4D3-42F7-9BEC-26833930E15D>.<34>"), _NSURLErrorFailingURLSessionTaskErrorKey=LocalDataTask <4D2BF55D-B4D3-42F7-9BEC-26833930E15D>.<34>, NSLocalizedDescription=cancelled} [-999]

I am running the app on an iPhone 5s as I've had to borrow an old phone from a friend

I don't get the error on the simulator.

The pictures do not sure nor the cards of the release version of the app.

Is it the fact the phone is slow/old so displaying is too much or is it an another type of error or something I haven't done in xcode/iOS that I should have?


Error while publishing component to Adalo

User uploaded FontFamily for React-native App

$
0
0

I am working on a react-native project, in which I have to implement a functionality in which user can set a custom theme for the app, the theme includes Theme color, font color and font family. The problem I'm facing right now is that the requirement for font family is that user can upload a custom font family from the application that will implemented throughout the application. I have searched about it but i haven't been able to find anything about how I can take a font family that user uploads and link it with my assets and then use it in my application.

Native android/ios Component support in cross platform mobile technologies

$
0
0

I have to build one SDK which has a native language code in Android. now i have to give support that SDK to the all kind of cross-platform technology like RN, Flutter, Ionic, Phonegap etc..

I am search a short way to give support of native language SDK to cross-platform technologies.

Please help.

What API/SDK to print automatically to thermal printer (e.g. Brother QL) with my React Native iPhone app without interaction?

$
0
0

I've been looking into different API/SDKs that would be best and easiest to integrate with my React Native iPhone app. This is an internal employee app, that once a form is submitted I would like to automatically print out a label from a thermal printer (e.g. Brother QL1110NWB).

Some options I found are:

React Native:

Brother SDK:

Apple AirPrint:

Does anyone have experience with any of these API/SDKs and can recommend best method for easy integration and be able to print directly without interaction?

Thank you!

expo-notifications - Error encountered while updating the device push token with the server

$
0
0

I'm using Expo's bare-workflow for my react-native project. I'm using expo's push notification service. I keep getting the following error whenever I try to get my expo push token:

[expo-notifications] Error encountered while updating the device push token with the server: {"error":"invalid_token","error_description":"The bearer token is invalid"}

I'm running the app directly on my device so should be able to get notifications.

I'm using basically the same registerForPushNotificationsAsync() that is provided in the documentation.

import Constants from 'expo-constants';import * as Notifications from 'expo-notifications';import { Platform } from 'react-native';export const registerForPushNotificationsAsync = async () => {  try {    if (Constants.isDevice) {      const experienceId = '@{username}/{slug}';      const {        status: existingStatus      } = await Notifications.getPermissionsAsync();      let finalStatus = existingStatus;      if (existingStatus !== 'granted') {        const { status } = await Notifications.requestPermissionsAsync();        finalStatus = status;      }      if (finalStatus !== 'granted') {        alert('Failed to get push token for push notification!');        return;      }      const token = (        await Notifications.getExpoPushTokenAsync({ experienceId })      ).data;      console.log('🏷🏷   Token :', token);      return token;    } else {      alert('Must use physical device for Push Notifications');    }    if (Platform.OS === 'android') {      Notifications.setNotificationChannelAsync('default', {        name: 'default',        importance: Notifications.AndroidImportance.MAX,        vibrationPattern: [0, 250, 250, 250],        lightColor: '#FF231F7C'      });    }    return undefined;  } catch (error) {    console.error('Error in registerForPushNotificationsAsync()', error);    return undefined;  }};

Expo packages in package.json

"expo": "~40.0.0","expo-analytics": "^1.0.16","expo-app-loading": "^1.0.1","expo-font": "~8.4.0","expo-image-manipulator": "~8.4.0","expo-image-picker": "~9.2.0","expo-intent-launcher": "~8.4.0","expo-notifications": "~0.8.2","expo-splash-screen": "~0.8.0","expo-updates": "~0.4.0",

I can't see anything about setting a bearer token, so I'm unsure what it could be after or where to even set it assuming I was able to determine what bearer token it is after.

Does anyone know what might be causing the problem?

React native html to pdf

$
0
0

I am using this code and it works fine in simulator as I am getting a location and can get pdf file from there

async createPDF() {    let options = {     html: '<h1>PDF          TEST</h1>',      fileName: 'test',     directory: 'Documents',  };   let file = await       RNHTMLtoPDF.convert(options)   //     console.log(file.filePath);      alert(file.filePath); }

But the above code problem in the real iOS mobile as it is saving the pdf file somewhere. I don’t know where but I am not able to see that file in my mobile. So can anyone tell me how can I save my file in the downloads or documents in the iOS . So that I can see the downloaded file.

Set up React Native project without using react-native-cli

$
0
0

So I'm learning React Native now, and I'm wondering how to set up an app manually, without using react-native-cli. The reason is that I want to set up app code within another project, but whenever I try to move code from a react-native-cli app to another folder containing other project code, I get build errors when running npx react-native run-ios (specifically, xcodebuild errors out with exit code 65). Actually, even if you create a project with react-native-cli and then just change the folder name you get the same build error.

I have template repos I use to start React projects, and I'd like to set one up for native projects, but it looks like it's not possible with the react-native-cli workflow. Is there another way to initialize a React Native project? I know the React docs have a section on integrating RN with existing native apps (https://facebook.github.io/react-native/docs/integration-with-existing-apps), but I don't have an existing native app, I'm starting a new one!

I have scoured the documentation and found nothing on this. Is there any way to find out what commands are run by react-native-cli? How can I set up my RN app from scratch?

EDIT: yes I have heard of Expo! It's all over the RN documentation. I'm asking about how to do the things that react-native init does, but with a more specialized/templated project structure.


How can I add the pod 'RNDateTimePicker' from @react-native-community/datetimepicker to my NPM project so it installs when users install the package?

$
0
0

How can I add the pod RNDateTimePicker from @react-native-community/datetimepicker to my NPM project so it installs when users install the package?

How can I make sure it's automatically downloaded when the user installs my NPM package? I've tried using peerDependencies, but I'm having no luck.

Can't select initial time value on ios

$
0
0

I'm using the 'react-native-community/datetimepicker' to set time on my App. When there is no time set I want to show the value '--:--'Because the time picker needs to get a Date object as the initial value I set the initial value of the date picker to be 12:00 AM.My problem is that ios don't let you choose the initial time you set as an initial value.The user that sees --:-- on the time input can't select 12:00 AM on the time picker and doesn't understand why. How can I solve it?

function MyTimer({ navigation }) {  const [from, setFrom] = useState('');  const [showFrom, setShowFrom] = useState(false);  const fromValue = !from?.length ? dayjs().toDate() : dayjs(from).toDate();  const onHoursChanged = (value, option) => {    if (!value) return;    return setFrom(value);  };  const onHoursSave = () => {    navigation.navigate('MyNextTime');  };  const DatePickerComponent = ({ type }) => {    if (Platform.OS === 'ios') {      return (<ActionSheet ref={type === FROM ? actionSheetRefFrom : actionSheetRefTo}><View><DateTimePicker              testID="dateFromToTimePicker"              value={fromValue}              mode="time"              minuteInterval={30}              display="spinner"              onChange={(event, value) => {                setShowFrom(false);                onHoursChanged(value);              }}            /></View></ActionSheet>      );    } else {      return showFrom && (<DateTimePicker              testID="dateFromTimePicker"              value={fromValue}              mode="time"              minuteInterval={30}              display="clock"              onChange={(event, value) => {                setShowFrom(false);                onHoursChanged(value, FROM);              }}            />          )    }  };  return (<View><View style={{ flex: 1, width: '100%' }}><View          style={{            paddingTop: 26,            paddingRight: 24,            paddingLeft: 24,          }}><View>Your hours</View><View>            Enter the hours</View></View><View style={{ flex: 1, justifyContent: 'flex-start' }}><Text style={{ marginTop: 70 }}>            Occurs</Text><View><TouchableOpacity              onPress={() => {                if (Platform.OS === 'ios') {                  actionSheetRefFrom.current?.setModalVisible();                  tapTimePicker();                } else {                  setShowFrom(true);                }              }}              style={styles.button}><Text subtitle color={BLUE} left>                From</Text><View style={{ flexDirection: 'row', alignItems: 'center' }}><Text style={{ paddingRight: 15 }}>                  {!from.toString().length ? '--:--' : dayjs(from).format('hh:mm a')}</Text></View></TouchableOpacity></View><DatePickerComponent/></View><View style={{ height: 106, width: '100%', justifyContent: 'center', alignItems: 'center' }}><Button            disabled={!from}            style={{ width: 280 }}            onPress={() => onHoursSave()}            type="main"            title="Next"          /></View></View></View>  );}

React native on XCode build successful but stuck at '100% on simulator

$
0
0

new to React Native here, I tried to build my expo project on XCode so I eject that and open in XCode. but when I tried to build it and run it show's me that build was successful but on simulator it stuck at '100%' and wont run. also on XCode I receive this:

enter image description here

anyone can help me with this?

How to customize keyboard in android and iOS?

$
0
0

enter image description hereAdd "next" and "previous" arrows to the keyboard in iOS. And Set the "return"/"next" button on the keyboard to take the user to the next field in react native.

How to customize keyboard in android and iOS using react-native properties?

$
0
0

How to Add "next" and "previous" arrows to the keyboard in iOS. And Set the "return"/"next" button on the keyboard to take the user to the next field in react native. enter image description here

RN App crash at launch on testflight review eventhough it works on release mode simulator

$
0
0

Hello wonderful community

I'm trying to upload my app to testflight but it keeps beeing rejected. When i try it on all types of simulator in release mode it works...

Here are a lot of informations but feel free to ask for more if needed. I hope there is a hero out-here to help a poor lad

Here is my stack :

  • "react": "17.0.1"
  • "react-native": "0.64.0"
  • Xcode 12.5
  • IOS v14.5

Here is the crash log i get :

Exception Type:  EXC_CRASH (SIGABRT)Exception Codes: 0x0000000000000000, 0x0000000000000000Exception Note:  EXC_CORPSE_NOTIFYTriggered by Thread:  7Application Specific Information:abort() called

Here is the Thread 7 crashing:

Thread 7 name:  Dispatch queue: com.facebook.react.ExceptionsManagerQueueThread 7 Crashed:0   libsystem_kernel.dylib          0x00000001b666d334 0x1b6644000 + 1687561   libsystem_pthread.dylib         0x00000001d3b0daa0 0x1d3b0b000 + 109122   libsystem_c.dylib               0x000000019208fb90 0x192018000 + 4903843   libc++abi.dylib                 0x000000019d86fbb8 0x19d85c000 + 808244   libc++abi.dylib                 0x000000019d860ec8 0x19d85c000 + 201685   libobjc.A.dylib                 0x000000019d76d05c 0x19d766000 + 287646   libc++abi.dylib                 0x000000019d86efa0 0x19d85c000 + 777287   libc++abi.dylib                 0x000000019d86ef2c 0x19d85c000 + 776128   libdispatch.dylib               0x00000001888fc800 0x1888f8000 + 184329   libdispatch.dylib               0x0000000188903fd4 0x1888f8000 + 4910810  libdispatch.dylib               0x0000000188904bd0 0x1888f8000 + 5217611  libdispatch.dylib               0x000000018890f48c 0x1888f8000 + 9537212  libsystem_pthread.dylib         0x00000001d3b0e7a4 0x1d3b0b000 + 1424413  libsystem_pthread.dylib         0x00000001d3b1574c 0x1d3b0b000 + 42828

Here are my dependencies:

"dependencies": {"@babel/plugin-transform-object-assign": "^7.12.13","@firebase/app": "^0.6.20","@firebase/auth": "^0.16.4","@firebase/auth-types": "^0.10.2","@react-native-async-storage/async-storage": "^1.15.2","@react-native-community/slider": "^3.0.3","@react-native-firebase/app": "^11.3.0","@react-native-firebase/auth": "^11.3.0","@react-native-firebase/database": "^11.3.0","@react-native-firebase/firestore": "^11.3.0","@react-native-firebase/storage": "^11.3.0","@react-native-google-signin/google-signin": "^6.0.0","@react-native-mapbox-gl/maps": "github:react-native-mapbox-gl/maps#master","@react-native-segmented-control/segmented-control": "^2.3.0","@react-navigation/drawer": "^5.12.5","@react-navigation/native": "^5.9.4","@react-navigation/stack": "^5.14.4","@reduxjs/toolkit": "^1.5.1","@turf/helpers": "^6.3.0","formik": "^2.2.6","geolib": "^3.3.1","lottie-react-native": "^4.0.2","mockdate": "^3.0.5","moment": "^2.29.1","node-fetch": "^2.6.1","pod-install": "^0.1.20","prop-types": "^15.7.2","ramda": "^0.27.1","react": "17.0.1","react-addons-shallow-compare": "^15.6.3","react-native": "0.64.0","react-native-animatable": "^1.3.3","react-native-background-fetch": "^4.0.2","react-native-chart-kit": "^6.11.0","react-native-date-picker": "^3.2.10","react-native-formik": "^1.7.8","react-native-geolocation-service": "^5.2.0","react-native-gesture-handler": "^1.10.3","react-native-image-picker": "^3.3.2","react-native-modal": "^11.10.0","react-native-progress": "^4.1.2","react-native-reanimated": "^2.1.0","react-native-redux": "^1.0.10","react-native-safe-area-context": "^3.2.0","react-native-safe-modules": "^1.0.0","react-native-scale-bar": "^1.0.6","react-native-screens": "^3.1.1","react-native-snap-carousel": "^3.9.1","react-native-svg": "^12.1.1","react-native-uuid-generator": "^6.1.1","react-native-vector-icons": "^8.1.0","react-native-video": "^5.1.1","react-redux": "^7.2.3","redux": "^4.0.5","redux-persist": "^6.0.0","redux-persist-filesystem-storage": "^3.0.0","redux-thunk": "^2.3.0","rn-fetch-blob": "^0.12.0","string-hash-64": "^1.0.3","typescript": "^4.2.4","uuid": "^8.3.2","yup": "^0.32.9"  },

At first i thought it was from fbsdk login so i stripped away the lib, did'nt work. I also tried to remove/update dependencies, did'nt work aswell.When i check the symbolicated crash log it seems to come from RTCNativeModule.mm or some stuff quite cryptic i don't quite understand ...

Thank you and have a nice day

React Native DuplicateError: Duplicated files or mocks

$
0
0

After updating xCode I am facing the below error from a week. I am not able to run app on device. I dont think the issue is with xcode because even if I try to run on android device the same issue occurs.

The issue occurs when we run npm start also with reset option the same error occurs.

The only option is to run on android device after deleting ios build folder.

The error

The following files share their name; please adjust your hasteImpl:    * <rootDir>/node_modules/react-native/package.json    * <rootDir>/ios/build/oleo/Build/Products/Debug-iphoneos/oleo.app/assets/node_modules/react-native/package.jsonFailed to construct transformer:  DuplicateError: Duplicated files or mocks. Please check the console for more info    at setModule (/Users/murtazakanpurwala/Documents/Work/Web_Design_Dev/Clients/Oleo/OleoCW/node_modules/jest-haste-map/build/index.js:620:17)    at workerReply (/Users/murtazakanpurwala/Documents/Work/Web_Design_Dev/Clients/Oleo/OleoCW/node_modules/jest-haste-map/build/index.js:691:9)    at processTicksAndRejections (internal/process/task_queues.js:93:5)    at async Promise.all (index 668) {  mockPath1: 'node_modules/react-native/package.json',  mockPath2: 'ios/build/oleo/Build/Products/Debug-iphoneos/oleo.app/assets/node_modules/react-native/package.json'}(node:8630) UnhandledPromiseRejectionWarning: Error: Duplicated files or mocks. Please check the console for more info    at setModule (/Users/murtazakanpurwala/Documents/Work/Web_Design_Dev/Clients/Oleo/OleoCW/node_modules/jest-haste-map/build/index.js:620:17)    at workerReply (/Users/murtazakanpurwala/Documents/Work/Web_Design_Dev/Clients/Oleo/OleoCW/node_modules/jest-haste-map/build/index.js:691:9)    at processTicksAndRejections (internal/process/task_queues.js:93:5)    at async Promise.all (index 668)(node:8630) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)(node:8630) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

Package.json

{"name": "oleo","version": "0.0.1","private": true,"scripts": {"start": "react-native start","test": "jest","lint": "eslint .","create-bundle-ios": "react-native bundle --platform ios --dev true --entry-file index.js --bundle-output ios/main.jsbundle","create-bundle-android": "react-native bundle --platform android --dev true --entry-file index.js --bundle-output android/app/src/main/assets/index.android.bundle --assets-dest android/app/src/main/res"  },"dependencies": {"@react-native-community/async-storage": "^1.9.0","@react-native-community/netinfo": "^5.8.0","@react-native-community/push-notification-ios": "^1.1.1","@react-native-firebase/analytics": "^6.7.1","@react-native-firebase/app": "^6.7.1","@react-native-firebase/auth": "^6.7.1","@react-native-firebase/firestore": "^6.7.1","@react-native-firebase/messaging": "^6.7.1","@react-native-firebase/storage": "^6.7.1","accordion-collapse-react-native": "^0.2.10","lodash": "^4.17.15","md5": "^2.2.1","moment": "^2.24.0","react": "16.8.6","react-native": "0.60.5","react-native-chooser": "^1.7.0","react-native-datepicker": "^1.7.2","react-native-draggable-flatlist": "^2.3.2","react-native-exit-app": "^1.1.0","react-native-gesture-handler": "^1.6.1","react-native-image-crop-picker": "^0.25.3","react-native-image-view": "^2.1.8","react-native-material-dropdown": "^0.11.1","react-native-modal": "^11.5.6","react-native-pdf": "^6.1.1","react-native-phone-input": "^0.2.4","react-native-popup-dialog": "^0.18.3","react-native-push-notification": "^3.2.1","react-native-reanimated": "^1.8.0","react-native-screens": "^2.7.0","react-native-snackbar": "^2.2.0","react-native-swiper": "^1.6.0","react-native-webview": "^7.4.2","react-navigation": "^4.3.8","react-navigation-stack": "^1.10.3","rn-fetch-blob": "^0.11.2"  },"devDependencies": {"@babel/core": "^7.9.0","@babel/runtime": "^7.9.2","@react-native-community/eslint-config": "^0.0.5","babel-jest": "^24.9.0","eslint": "^6.8.0","jest": "^24.9.0","metro-react-native-babel-preset": "^0.56.4","react-test-renderer": "16.8.6"  },"jest": {"preset": "react-native"  }}

I have deleted multiple times node modules, did a fresh install as well but the issue comes up every time.


React Native: How to move to the next input filed after pressing the “next” keyboard button?

$
0
0
<TextInput            // ...            returnKeyType = {"next"}            returnKeyType='go'          />

this codeenter image description here is not leading the 'go'/'next' to next input fieldHow to Add "next" and "previous" arrows to the keyboard in iOS. And Set the "return"/"next" button on the keyboard to take the user to the next field in react native.

React native react-native-html-to-pdf saving in iOS in internal storage

$
0
0

I am using this code and getting and this is saving the pdf file in internal storage in the IOS and I am not able to access this file so how can I store this file in the storage so that I can access it

 async createPDF() {    let options = {      html: '<h1>PDF TEST</h1>',      fileName: 'test',      directory: 'Documents',    };    let file = await RNHTMLtoPDF.convert(options)    // console.log(file.filePath);    alert(file.filePath);  }

Expo using fetch get empty data with status 200 in iOS

$
0
0

What I encountered

As the title suggested, when I perform fetch in iOS expo, the status code is 200, but the response data is empty(undefined).

What I'm trying to do here is to fetch the html content of that url, and then using regex to parse the specific NetFlow(GB) data inside.

What I expected

I hope someone could tell me what I can do to correctly get the html content back from the url. Below is what I've tried and thought of as the possible issues. Hope these can help you got a better understanding of the problem.

What I've tried and observed

  1. I also tested the code with another https url, the result is just fine. fetch correctly got the data back.
  2. The weirdest one. I tried the same code on an Android device, it worked and got the html content perfectly, so I can further use regex to parse and do what I want.I guess maybe it's because the different implementation of fetch on Android and iOS, just like fetch is differently implemented across browsers.
  3. I think it's not because of Apple's policy on banning http connection, because the url is https.
  4. I found that the very difference between Android and iOS response headers is that the transfer-encoding is Identity(iOS) / chunked(Android). I guess maybe it's because with Identity set in iOS fetch, the data transferred is not complete, and further causing the empty data.
  5. There's no error message, because as I mentioned, the status code is 200.

How to duplicate

  • expo version: 41.0.0
  • testing phone: iPhone 12 mini(iOS 14.4.2)

The smallest code snippets to duplicate(Using the above environment):

const response = await fetch(`https://uncia.cc.ncu.edu.tw/dormnet/index.php?section=netflow&ip=140.115.200.135`);console.log(await response.text())        // it's empty hereconsole.log(await response.status)        // http status 200 here

The response header

"Cache-Control": "no-store, no-cache, must-revalidate, post-check=0, pre-check=0","Connection": "Keep-Alive","Content-Type": "text/html","Date": "Tue, 18 May 2021 13:46:11 GMT","Expires": "Thu, 19 Nov 1981 08:52:00 GMT","Keep-Alive": "timeout=5, max=100","Pragma": "no-cache","Set-Cookie": "TS011966fc=01f649e4032b53f69a5698d13692a46269a72f7efc7e7dfdb2ea104dff0fe73a79d3a368ef3392a89a5c83c3961d60de17ead07658; Path=/","Transfer-Encoding": "Identity",

Is there a way to sign a user up for a free trial WITHOUT auto-renewal (On App/Google Play store)

$
0
0

It seems like when a subscription ends, the user is automatically billed for the full subscription, but I don't want that to happen, I just want the promo to end with no hassle, so people won't be so hesitant to accidentally be charged.

React Native Expo: How to use an image stored locally on a phone emulator?

$
0
0

I am using React Native and Expo to make a mobile application in which one of the features is that the user can upload a form that includes an image. I am using expo ImagePicker: https://docs.expo.io/versions/latest/sdk/imagepicker/ to select the image or take a picture with a camera and then using Expo Media Library https://docs.expo.io/versions/latest/sdk/media-library/ to save the image locally to a folder on my phone emulator labelled "AppPhotos". I am using BlueStack for the phone emulator. The images are successfully being saved to the AppPhotos folder in the Media Manager in BlueHost. Here is the code for entering the form and saving the photo:

Form Submit

import React, { useEffect, useState } from 'react';import { Button, View, Text, TextInput, Picker } from 'react-native';import { styles } from './styles.js';import * as ImagePicker from 'expo-image-picker';import * as MediaLibrary from 'expo-media-library';const FormSubmit = ({navigation, route}) => {    const [Name, onChangeName] = useState(null);    const [Phone, onChangePhone] = useState(null);    const [Email, onChangeEmail] = useState(null);    const [selectedValue, setSelectedValue] = useState(null);    const [MileMarker, onChangeMileMarker] = useState(null);    const [Comments, onChangeComments] = useState(null);    const [RoadName, onChangeRoadName] = useState(null);    const [image, setImage] = useState(null);    const [hasPermission, setHasPermission] = useState(null);    const counties = ["Barbour", "Berkeley", "Boone", "Braxton", "Brooke", "Cabell", "Calhoun", "Clay", "Doddridge", "Fayette", "Gilmer", "Grant", "Greenbrier", "Hampshire", "Hancock", "Hardy","Harrison", "Jackson", "Jefferson", "Kanawha", "Lewis", "Lincoln", "Logan", "Marion", "Marshall", "Mason", "Mercer", "Mineral", "Mingo", "Monongalia", "Monroe", "Morgan", "McDowell","Nicholas", "Ohio", "Pendleton", "Pleasants", "Pocahontas", "Preston", "Putnam", "Raleigh", "Randolph", "Ritchie", "Roane", "Summers", "Taylor", "Tucker", "Tyler", "Upshur", "Wayne", "Webster", "Wetzel", "Wirt", "Wood", "Wyoming"]    const pickImage = async () => {      let result = await ImagePicker.launchImageLibraryAsync({      mediaTypes: ImagePicker.MediaTypeOptions.All,      allowsEditing: true,      aspect: [4, 3],      quality: 1,      });      console.log(result);      if (!result.cancelled) {      setImage(result.uri);      }    };    const takeImage = async () => {      let result = await ImagePicker.launchCameraAsync({      mediaTypes: ImagePicker.MediaTypeOptions.All,      allowsEditing: true,      aspect: [4, 3],      quality: 1,      });      console.log(result);      if (!result.cancelled) {      setImage(result.uri);      }    };  //This needs to happen when I press the button I think but it doesnt really seem to work if I dp.  useEffect(() => {    (async () => {      if (Platform.OS !== 'web') {        const { status } = await ImagePicker.requestMediaLibraryPermissionsAsync();        if (status !== 'granted') {          alert('Sorry, we need camera roll permissions to make this work!');        }      }      const {status} = await ImagePicker.requestCameraPermissionsAsync();      setHasPermission(status === 'granted');    })();  }, []);  if (hasPermission === null) {    return <View />;  }  if (hasPermission === false) {    return <Text>No access to camera</Text>;  }    //POST a new form to the database    const postForm = async () =>{      console.log("Image URI: " + image);      fetch('http://10.0.2.2:5000/forms', {        method: 'POST',        headers: {'Accept': 'application/json','Content-Type': 'application/json',        },        body: JSON.stringify({          Name: Name,          Phone: Phone,          Email: Email,          County: selectedValue,          RoadName: RoadName,          MileMarker: MileMarker,          Comments: Comments,          Path: image        })      }).then(response =>{        if(response.ok){          return response.json();        }      }).then(data => console.log(data));    }    const SaveToPhone = async (item) => {      // Remember, here item is a file uri which looks like this. file://..      const permission = await MediaLibrary.requestPermissionsAsync();      if (permission.granted) {        try {          const asset = await MediaLibrary.createAssetAsync(item);          MediaLibrary.createAlbumAsync('AppPhotos', asset, false)            .then(() => {              console.log('File Saved Successfully!');            })            .catch(() => {              console.log('Error In Saving File!');            });        } catch (error) {          console.log(error);        }      } else {        console.log('Need Storage permission to save file');      }    };  return (<View style={styles.container}><Text>Submit a complaint form.</Text><View style={styles.rowContainer}><Text style={styles.myText}>Name</Text><TextInput            style={styles.input}            onChangeText={onChangeName}            value={Name}            /></View><View style={styles.rowContainer}><Text style={styles.myText}>Phone</Text><TextInput            style={styles.input}            onChangeText={onChangePhone}            value={Phone}            /></View><View style={styles.rowContainer}><Text style={styles.myText}>Email</Text><TextInput            style={styles.input}            onChangeText={onChangeEmail}            value={Email}            /></View><View style={styles.rowContainer}><Picker                style={styles.charPicker}                mode="dropdown"                selectedValue={selectedValue}                onValueChange={(itemValue, itemIndex) => setSelectedValue(itemValue)}>                {counties.map((item, index) => {                    return (<Picker.Item label={item} value={item} key={index}/>)                 })}</Picker></View><View style={styles.rowContainer}><Text style={styles.myText}>Mile Marker</Text><TextInput            style={styles.input}            onChangeText={onChangeMileMarker}            value={MileMarker}            /></View><View style={styles.rowContainer}><Text style={styles.myText}>Road Name</Text><TextInput            style={styles.input}            onChangeText={onChangeRoadName}            value={RoadName}            /></View><View style={styles.rowContainer}><Text style={styles.myText}>Comments</Text><TextInput            style={styles.textArea}            numberOfLines={10}            multiline={true}            onChangeText={onChangeComments}            value={Comments}            /></View><Button title="Pick an image from camera roll" onPress={pickImage} /><Button title="Take a picture" onPress={takeImage} /><Button                style = {styles.button}                title="Submit"                        onPress={() => {                          SaveToPhone(image);                          postForm();                        }}                color="#19AC52"            /></View>  );}export default FormSubmit;

These forms (including the image URI) are saved to an SQL database. This is an example of one of the image uri's that is stored as "Path" :

file:///data/user/0/host.exp.exponent/cache/ExperienceData/UNVERIFIED-10.69.64.21-DOH_Mobile_V1/ImagePicker/582fb57f-2ff9-477e-886b-de26e0f03c4b.jpg

However, when I try to loop over and display the existing forms I can not get the images. If you notice, for each card I can simply use item.Name or item.Phone which works fine. However for some reason this does not work with the image URI. Here is the code for that:

Forms Screen

import React, { useEffect, useState } from 'react';import { View, Text, FlatList, ScrollView, Image } from 'react-native';import { Card } from 'react-native-elements'import { styles } from './styles.js';import * as ImagePicker from 'expo-image-picker';const FormsScreen = ({navigation, route}) => {  const [formsArray, setFormsArray] = useState([]);  //Fetch all users from database  useEffect(() =>{    fetch('http://10.0.2.2:5000/forms').then(response =>{      if(response.ok){        return response.json();      }    }).then(data => setFormsArray(data));  }, []);  for(var i = 0; i<formsArray.length; i++){    console.log(formsArray[1].Path);  }  return (<FlatList         keyExtractor={(item) => item.ID.toString() }        style = {styles.List}        data={formsArray}        renderItem={({item}) => (<Card><Card.Title>{item.ID}</Card.Title><Card.Divider/><View style={styles.Container}><Text>{item.Comments}</Text><Image source={require(item.Path)} /><Text>{item.RoadName}</Text></View><View style={styles.ListContainer}><Text style={styles.LabelText}>Name</Text><Text style={styles.LabelText}>Phone</Text><Text style={styles.LabelText}>Email</Text></View><View style={styles.ListContainer}><Text style={styles.CardText}>{item.Name}</Text><Text style={styles.CardText}>{item.Phone}</Text><Text style={styles.CardText}>{item.Email}</Text></View></Card>        )}        />  );}export default FormsScreen;

I have some hunches about why this doesn't work. First of all, with using just the image URI there is no way for the Forms Screen to know what folder the images are stored in or even that they are stored locally on the device. So how can I direct the code to look for that image URI in the emulated phones Media Manage > AppPhotos folder? Also, once stored inside the AppPhotos folder the name of the image is simply everything after /ImagePicker/.

How can I remedy this issue? Am I approaching this incorrectly?

Viewing all 16907 articles
Browse latest View live


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