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

React Native app crash on ios 13.3.1 after I updated to latest ios version

$
0
0

I am running react native app on ios simulator(13.3) and on ipad(13.1.1). on simulator it is working fine . Previously it was working fine on ipad also but ipad got updated to 13.3.1 . Since than on ipad it is crashing on white screen within fraction of seconds. Any idea to fix it?

↧

Expo react native app image not work properly on testflight ios

$
0
0

I have an app login page centered on screen. When i test on locally with expo on win server and also tested mac on a simulator it works perfectly but when i do build-ios and put it to appstore and test with testflight it is not working properly.

This code works on android also. What am i doing wrong?

You can check full code on github with master branch : https://github.com/saricabasak/keyholder I also share releated codes below that you can check fast

View that i run expo on locally:

enter image description here

on testflight:

enter image description here

app.json

{
  "expo": {
    "name": "key-holder",
    "slug": "key-holder",
    "privacy": "public",
    "sdkVersion": "35.0.0",
    "platforms": [
      "ios",
      "android",
      "web"
    ],
    "version": "1.1.0",
    "orientation": "portrait",
    "icon": "./assets/kilit_logo_logo_500x500.png",
    "splash": {
      "image": "./assets/kilit_logo_logo_1000x1000.png",
      "resizeMode": "contain",
      "backgroundColor": "#DAD7C5"
    },
    "updates": {
      "fallbackToCacheTimeout": 0
    },
    "assetBundlePatterns": [
      "**/*"
    ],
    "ios": {
      "supportsTablet": false,
      "bundleIdentifier": "com.coderals.keyholder",
      "buildNumber": "1.0.0"
    },
    "android": {
      "package": "com.coderals.keyholder",
      "versionCode": 1
    },
    "androidStatusBar": {
      "barStyle": "light-content",
      "backgroundColor": "#334393"
    },
    "description": ""
  }
}

image Code:

import logo from '../../assets/transparentLogo.png';


export default class KeyHolderContainer extends Component {
  render() {
    let renderLogo;
    let renderText;
    if (this.props.isLogin) {
      renderLogo = (
        <Image
          source={logo}
          style={container.logoStyle}
          resizeMode="center"
        />
      );
      renderText = (
        <Text style={container.titleStyle}>
          {translate("KeyHolderWelcome")}
        </Text>
      );
    }

    return (
      <Container style={container.containerStyle}>
        {renderLogo}
        {renderText}
        {this.props.children}
      </Container>
    );
  }
}

styles:

export const container = StyleSheet.create({
  containerStyle: {
    width: "100%",
    height: "100%",
    backgroundColor: getStyle("container.backgroundColor")
  },
  logoStyle: {
    width: "40%",
    height: "40%",
    alignSelf: "center"
  },
  titleStyle: {
    color: getStyle("container.titleColor"),
    fontSize:20,
    fontWeight: "bold",
    alignSelf: "center"
  }
});

the image size : 500 x 500 on asset folder.

↧
↧

React native iOS how to make background process after getting new remote notification, without opening the app

$
0
0

I use react-native-firebase to get remote notification, and i want after getting remote notification(data-only) to do some process in background, without opening the app (without tapping on the notification).

  • I achieved that in android with Headless JS.

  • I really want to find how to do that in iOS

I read about:

  1. Notification Service Extension - https://developer.apple.com/documentation/usernotifications/unnotificationserviceextension

  2. https://github.com/react-native-webrtc/react-native-voip-push-notification

But I didn't get it to work, maybe someone has experience with this situation?

↧

How to prevent layout from overlapping with iOS status bar

$
0
0

I am working on tutorial for React Native navigation. I found out that all layout starts loading from top of screen instead of below of the status bar. This causes most layouts to overlap with the status bar. I can fix this by adding a padding to the view when loading them. Is this the actual way to do it? I don' think manually adding padding is an actual way to solve it. Is there a more elegant way to fix this?

import React, { Component } from 'react';
import { View, Text, Navigator } from 'react-native';

export default class MyScene extends Component {
    static get defaultProps() {
            return {
                    title : 'MyScene'    
            };  
    }   
    render() {
            return (
                    <View style={{padding: 20}}> //padding to prevent overlap
                            <Text>Hi! My name is {this.props.title}.</Text>
                    </View> 
            )   
    }    
}

Below shows the screenshots before and after the padding is added. enter image description here

↧

React-Native - Missing Class Properties Transform

$
0
0

I have upgraded React-Native and Android studio yesterday and since then my App hasnt been running

react-native-cli: 2.0.1 react-native: 0.60.4 Android-Studio : 3.6.1

The app runs correctly without any errors on the Xcode but shows

Missing Class properties Transform

enter image description here

↧
↧

Can't get background tasks to work in React-Native

$
0
0

I need to frequently write into a text file, let's say write a timestamp into a file with react-native in iOS and android. I wrote an app by the help of the following libraries. On android, the app is working perfectly fine, but on iOS not working properly.

I tried to use these libraries:

  1. react-native-background-task
  2. react-native-background-fetch
  3. react-native-background-queue + react-native-background-task

But none of them works fine:

  1. with react-native-background-task: the file is written randomly 5-6 times a day or less
  2. with react-native-background-fetch: the file is written randomly 3-4 times a day or less
  3. react-native-background-queue + react-native-background-task: the file is not written AT ALL!

Would you please tell me if these behaviors are normal, and if not, what am I doing wrong???

Any help would be greatly appreciated.

Here are my codes:

In order to use react-native-background-task:

import React from 'react'
import Mytest from './test';
import BackgroundTask from 'react-native-background-task'
import {
    Text,
    View,
  } from 'react-native';

BackgroundTask.define(() => {
  console.log('Hello from a background task')
  Mytest.writeFiles()
  BackgroundTask.finish()
})

export default class MyApp extends React.Component {

  componentDidMount() {
    BackgroundTask.schedule()
  }

  render() {
    return(
     <View>
      <Text>Hello world</Text>
    </View>)
  }

}

In order to use react-native-background-fetch:

import React, { Component } from 'react';
import {
    Text,
    View,
    StyleSheet
  } from 'react-native';
import BackgroundFetch from "react-native-background-fetch";

var RNFS = require('react-native-fs');
var path = RNFS.DocumentDirectoryPath + '/fetch.txt';
var count = 0

export default class App extends Component {

  constructor(props) {
    super(props);
    this.state = {
      date: '',
    }
  }

  componentDidMount() {
    BackgroundFetch.configure({
      stopOnTerminate: false,
      startOnBoot: true,
      requiredNetworkType: BackgroundFetch.NETWORK_TYPE_NONE,
      requiresCharging: false,      // Default
      requiresDeviceIdle: false,    // Default
      requiresBatteryNotLow: false, // Default
      requiresStorageNotLow: false  // Default
    }, () => {
      console.log("[js] Received background-fetch event");
      this.writeFiles()
      BackgroundFetch.finish(BackgroundFetch.FETCH_RESULT_NEW_DATA);
    }, (error) => {
      console.log("[js] RNBackgroundFetch failed to start");
    });

    BackgroundFetch.status((status) => {
      switch(status) {
        case BackgroundFetch.STATUS_RESTRICTED:
          console.log("BackgroundFetch restricted");
          break;
        case BackgroundFetch.STATUS_DENIED:
          console.log("BackgroundFetch denied");
          break;
        case BackgroundFetch.STATUS_AVAILABLE:
          console.log("BackgroundFetch is enabled");
          break;
      }
    });
  }

  render() {
        return (
          <View style={styles.container}>
            <Text style={styles.welcome}>
              Welcome to React Native!
            </Text>
          </View>
        );
      }


  getDate() {
    var that = this;
    var date = new Date().getDate(); //Current Date
    var month = new Date().getMonth() + 1; //Current Month
    var year = new Date().getFullYear(); //Current Year
    var hours = new Date().getHours(); //Current Hours
    var min = new Date().getMinutes(); //Current Minutes
    var sec = new Date().getSeconds(); //Current Seconds
    that.setState({
      date:
        date + '/' + month + '/' + year + '' + hours + ':' + min + ':' + sec,
    });
  }


writeFiles = async () => {
  this.getDate()
    try {
      for(let i = 0; i < 1; i++){
        count = count + 1;
        console.log(count);
        RNFS.appendFile(path, '  \n  '+ count + '  \n  ' + this.state.date , 'utf8')
        .then((success) => {
        })
      }
    }catch (err) {
      console.warn("error", err);
    } 
}          

};

In order to use react-native-background-queue + react-native-background-task:

import React, { Component } from 'react';
import Mytest from './test';
import BackgroundTask from 'react-native-background-task'
import {Platform,...} from 'react-native';
import queueFactory from 'react-native-queue';

BackgroundTask.define(async () => {
  queue = await queueFactory();
  queue.addWorker('background-example', async (id, payload) => {
  if (payload.name == 'sima') {
     Mytest.writeFiles()
     console.log('Hello from a background task ')}
  });
  await queue.start(20000); 
  BackgroundTask.finish();
});

export default class App extends Component<{}> {

  constructor(props) {
    super(props);

    this.state = {
      queue: null,
      data: null,
    };

    this.init();

  }

  async init() {
    const queue = await queueFactory();
    queue.addWorker('background-example', async (id, payload) => {
    });

    this.setState({
      queue
    });

  }

  componentDidMount() {
    BackgroundTask.schedule(); 
  }

  makeJob(jobName, payload = {}) {
    console.log('job is created but will not execute until the above OS background task runs in ~15 min');
    this.state.queue.createJob(jobName, payload, {
     timeout: 5000
    }, false); 
  }


  render() {
    let output = 'No data loaded from OS background task yet.';
    if (this.state.data) {
      output = JSON.stringify(this.state.data);
    }

    return (
      <View style={styles.container}>
        <Text style={styles.welcome}>
          Welcome to React Native!
        </Text>
        <Text>Click buttons below to add OS background task jobs.</Text>
        <Text>Then Close App (task will not fire if app is in focus).</Text>
        <Text>Job will exec in ~15 min in OS background.</Text>
        {this.state.queue && <Button title={"Press To Queue sima Job"} onPress={ () => { this.makeJob('background-example', { name: 'sima' }) } } /> }
        {this.state.queue && <Button title={"Press To Queue another Job"} onPress={ () => { this.makeJob('background-example', { name: 'simsim' }) } } /> }
        <Text>{output}</Text>
      </View>
    );

  }


}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
  welcome: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  },
});

And here is test.js:

var RNFS = require('react-native-fs');
var path = RNFS.DocumentDirectoryPath + '/test.txt';
var count = 0;

const Mytest = {

  writeFiles: () => {
    var that = this;
    var date = new Date().getDate(); //Current Date
    var month = new Date().getMonth() + 1; //Current Month
    var year = new Date().getFullYear(); //Current Year
    var hours = new Date().getHours(); //Current Hours
    var min = new Date().getMinutes(); //Current Minutes
    var sec = new Date().getSeconds(); //Current Seconds
    var date = date + '/' + month + '/' + year + '' + hours + ':' + min + ':' + sec

      try {
        for(let i = 0; i < 1; i++){
          count = count + 1;
          console.log(count);
          RNFS.appendFile(path, '  \n  '+ count + '  \n  ' + date , 'utf8')
          .then((success) => {
            console.log('FILE WRITTEN!');
          })
        }
      }catch (err) {
        console.warn("error", err);
      } 
  }
  }
  export default Mytest;
↧

React-native: display foreground notifications like background notifications with zo0r/react-native-push-notification

$
0
0

I have set up push notifications on my React-native app with zo0r / react-native-push-notification . It works on Android, and on iOS when the app is in background mode.

However, the notification does not display when the app is in foreground mode with iOS. I'm aware that I have to handle the notification when in foreground mode but I'd like to display them exactly the same way there are displayed when in background mode.

So I did the following:

PushNotification.configure({
...
   onNotification: function(notification) {
      if (notification.foreground) {
         PushNotification.localNotification(notification);
      }
   },
...
}

But noting happens, the notification is still not displayed, what am I missing?

↧

Bluetooth background scan to help fight COVID-19

$
0
0

We're building a pro bono, anonymous app here to help fight coronavirus. You can find out more at viruscontact.com.

See the full user journey here https://drive.google.com/open?id=17c00e2kF7ge1I94_TnvZlCucknQ7Pe7t&fbclid=IwAR2TjbPHYGb_uQfgITHlO1lPGQBBtE7XbhVZHKTym50aXgte5ZRkwCtESjs

I'm trying to scan devices on iOS when the app is in background mode. I've learned that I have to tell explicitly what service ID I'm looking for. I was trying with 180F which is the battery service but it didn't find anything. Is it possible at all on IOS? It works well on Android.

I'm using the react-native-ble-manager package.

Can you tell me maybe a common service UUID what every phone advertises?

My aim is to track every contact with phones which are near me and it should work when the app is in background mode.

I am interested in other approaches even if they're not React Native. It must be possible on iOS as well as other apps already use it. (eg. Happen).

↧

Notification status suddenly "undetermined" for all builds

$
0
0

I am building an ejected Expo app (React Native w/ ExpoKit), and have recently run into an issue with notifications. I had them working previously with no issue, but recently, that suddenly changed, even though I didn't change anything relating to the notifications. Note that I am only using local notifications.

Anytime I try to add a notification, I get an "undetermined" status code, thus I can't add register notifications. This happens in the simulator, app built on device, and app distributed through TestFlight.

I tried downloading an older app version from TestFlight that had worked no problem before, but now I get the "undetermined" code on that version to! Does this mean that my device is the issue?

Thanks for any help you can give.

↧
↧

react- native how to make background process with silent data only notification

$
0
0

I want after getting remote notification(data-only) to do some process in background, without opening the app in iOS(i find out that it impossible in iOS because data only get to the app when user open the app).

I find that the best way to do that is - react-native-voip-push-notification with the voip, but i don't know how to implement it without use the push kit(because i'm not interesting in getting calls)-

"If you want to initiate a VoIP call without using CallKit, register for push notifications using the UserNotifications framework instead of PushKit. For more information, see UserNotifications."

Maybe someone did it and can show me example that i can use with react native because i don't know native code

↧

Why are Firestore requests hanging in published iOS app but not Expo client?

$
0
0

I'm building an app with React Native and Expo which uses Firestore as a database. In all my testing in the Expo Client app on iOS my requests to Firestore have been fine, but now I have a build in Apple's TestFlight and all requests to Firestore (reads and writes) are just hanging, leaving loading spinners on the screen (I've added debug text as well so I'm certain it's only Firestore requests).

Since I'm using Expo to build my app, I'm using the Firebase JS SDK as react-native-firebase is not available to use in Expo environments. This could be a problem, but it is the recommended way to use Firebase in the Expo docs. Any ideas as to why this could be happening?

↧

Integrating the React-Native component inside the custom native framework in swift

$
0
0

Prequisites: I am able to integrate the react-native component inside the native iOS swift application. To achieve this I used following links

  1. https://reactnative.dev/docs/0.6/communication-ios

  2. https://www.raywenderlich.com/945-react-native-tutorial-integrating-in-an-existing-app

  3. https://github.com/react-native-community/react-native-webview/blob/master/docs/Getting-Started.md

  4. https://medium.com/@bogdan.bolchis/integrating-react-native-with-an-existing-ios-app-ce6f68e55e13

Objective - I want to integrate the react-native component inside the native swift based custom framework. And then that framework is going to be used inside the native host application.

Following are some of the screen shots of the framework project which is compiling without error.

enter image description here

enter image description here

After the framework is compiled successfully. I added that framework inside the HostApp which is native iOS application coded in swift. As shown below.

enter image description here

That was giving compile time error as shown below.

enter image description here

Anyhow I wanted to at least compile the HostApp. I did add the dependencies mentioned in the error inside the project as shown in the following screenshot.

enter image description here

Then also it was giving the same error.

Please help me if anybody has any solution/suggestion on this. It will be really appreciated.

↧

React-Native-image-picker changes bottom tabs text colors

$
0
0

I have faced a kind of problem with react-native-image-picker.

On iOS, when user opens Image picker (doesn't matter whether to pick image or press "Cancel"), after closing, bottoms tabs wix/react-native-navigation text color changes to blue.

Android works well.

I have tried to use mergeOptions() func to change it back directly, but it didn't work, maybe I have done something wrong, but nevertheless I'm in deadlock with this problem.

Here is how image-picker func looks:

    ImagePicker.showImagePicker({ title: 'Pick photo' }, res => {
      if (res.didCancel) {
        console.log('User cancelled');
      } else if (res.error) {
        console.log('Error', res.error);
      } else {
        this.setState({
          fileType: res.type,
          fileName: res.fileName,
          uri: res.uri,
        });
        this.postAvatarImage();
      }
    });
  };

Thanks in advance, hope you can help me.

↧
↧

Green box shown in heatmap , using react-native-maps on iOS simulator

↧

Self signed certificate not working on xcode simulator (using react native webview)

$
0
0

I've applied all the changes in info.plist. I've also installed certificate on simulator, but no luck.

Still getting the error:

Blockquote "code": -1202, "description": "The certificate for this server is invalid. You might be connecting to a server."

What might be causing this error?

↧

Is it possible to upload a video to YouTube through React Native?

$
0
0

I'm currently attempting to create an app that allows users to upload to Youtube. The app also allows users to view this playlist. I know that the latter function is easily implemented, but I have not seen a similarly simple way to upload videos. I think it should be possible, but I'm wondering if there is some restriction (perhaps due to the existence of the YouTube application that would prevent this from being implemented.

Please advise.

Thanks very much.

↧

compiler-generated crash in Swift in my react-native app

$
0
0

My healthkit swift code keeps crashing in the background in production, and I can't figure it out for the life of me. I am fairly new to Swift, so maybe I am making a fundamental error in my implementation.

Features of the crash:

  • It seems to happen only in production. (our internal test program contains 10 devices only (so maybe it is co-incidence that it doesn't get picked up there).
  • Occurs in iOS versions - 10,11,12,13
  • Occurs for a very small set of users (1.5% of active audience), but very frequently for these same users.

Please find the crash log from my Crashlytics account below.

Crashed: com.facebook.react.HKManagerQueue
0  stepapp                      0x100f4f324 specialized HKManager.getTotal(_:typeStr:unit:options:completion:) + 4372984612 (<compiler-generated>:4372984612)
1  stepapp                      0x100f52e04 HKManager._getTotals(_:completion:) + 397 (HKManager.swift:397)
2  stepapp                      0x100f532ac @objc HKManager.getTotals(_:resolver:rejecter:) + 4373000876 (<compiler-generated>:4373000876)
3  CoreFoundation                 0x1af698c20 __invoking___ + 144
4  CoreFoundation                 0x1af568d30 -[NSInvocation invoke] + 300
5  CoreFoundation                 0x1af569908 -[NSInvocation invokeWithTarget:] + 76
6  stepapp                      0x101184e6c -[RCTModuleMethod invokeWithBridge:module:arguments:] + 241556
7  stepapp                      0x101187248 facebook::react::invokeInner(RCTBridge*, RCTModuleData*, unsigned int, folly::dynamic const&) + 250736
8  stepapp                      0x101186fac invocation function for block in facebook::react::RCTNativeModule::invoke(unsigned int, folly::dynamic&&, int) + 250068
9  libdispatch.dylib              0x1af35e610 _dispatch_call_block_and_release + 24
10 libdispatch.dylib              0x1af35f184 _dispatch_client_callout + 16
11 libdispatch.dylib              0x1af30b404 _dispatch_lane_serial_drain$VARIANT$mp + 608
12 libdispatch.dylib              0x1af30bdf8 _dispatch_lane_invoke$VARIANT$mp + 420
13 libdispatch.dylib              0x1af315314 _dispatch_workloop_worker_thread + 588
14 libsystem_pthread.dylib        0x1af3aeb88 _pthread_wqthread + 276
15 libsystem_pthread.dylib        0x1af3b1760 start_wqthread + 8

I have attached my implementation below, which contains the line mentioned in the crash logs

func _getTotals(_ options: Dictionary<String, Any>, completion: @escaping (Dictionary<String, Double>?) -> Void) {
    var stepsDone = false;
    var distanceDone = false;
    var caloriesDone = false;

    let steps = HKQuantityType.quantityType(forIdentifier: .stepCount);
    let distance = HKQuantityType.quantityType(forIdentifier: .distanceWalkingRunning);
    let calories = HKQuantityType.quantityType(forIdentifier: .activeEnergyBurned);

    var results = Dictionary<String, Double>();

    // 👇 THIS IS LINE 397 which is indicated in the crash report above
    self.getTotal(steps!, typeStr: HKManager.STEP_TYPE_STR, unit: HKUnit.count(), options: options) { (totalSteps, error) in
      stepsDone = true;
      if (totalSteps != nil) {
        results["steps"] = totalSteps;
      }

      if (stepsDone == true && distanceDone == true && caloriesDone == true) {
        return completion(results);
      }
    }

    self.getTotal(distance!, typeStr: HKManager.DISTANCE_TYPE_STR, unit: HKUnit.meter(), options: options) { (totalDistance, error) in
      distanceDone = true;
      if (totalDistance != nil) {
        results["distance"] = totalDistance;
      }
      if (stepsDone == true && distanceDone == true && caloriesDone == true) {
        return completion(results);
      }
    }

    self.getTotal(calories!, typeStr: HKManager.CALORIES_TYPE_STR, unit: HKUnit.kilocalorie(), options: options) { (totalCalories, error) in
      caloriesDone = true;
      if (totalCalories != nil) {
        results["calories"] = totalCalories;
      }
      if (stepsDone == true && distanceDone == true && caloriesDone == true) {
        return completion(results);
      }
    }
  }

I have also attached my implementation of the self.getTotal(...) function which is used in the above code. Point to note in this function, I switch to performing my HealthKit query in the background qos to ensure that these queries don't run on the main thread. I think it might be the cause for the crash.


  func getTotal(_ type: HKQuantityType, typeStr: String, unit: HKUnit, options: Dictionary<String, Any>, completion: @escaping (Double?, Error?) -> Void) {
    guard (self.healthStore != nil) else {
      let error = NSError(domain: "Healthkit not initialized", code: 50, userInfo: [:]);
      return completion(nil, error);
    }

    var start: Date;

    if (options["startDate"] != nil) {
      start = self.strToDate(dateStr: options["startDate"] as! String);
    } else {
      let date = Date()
      let cal = Calendar(identifier: .gregorian)
      let midnight = cal.startOfDay(for: date);

      start = midnight;
    }

    var ignoreMin = false;
    if (options["ignoreMin"] != nil) {
      ignoreMin = options["ignoreMin"] as! Bool;
    }

    if (ignoreMin != true && start < self.minStartDate && self.minStartDate != nil) {
      start = self.minStartDate;
    }

    var end: Date = Date();
    if (options["endDate"] != nil) {
      end = self.strToDate(dateStr: options["endDate"] as! String);
    }

    var sources = options["sources"] as? [String];
    if (sources == nil || (sources?.capacity)! < 1) {
      sources = ["com.apple.health."];
    }

    DispatchQueue.global(qos: .background).async { [weak self] in

      // fetch sources
      self?.getSources(sampleTypeStr: typeStr, sampleType: type, sources: sources!) { (s, error) in

        if (s == nil || ((s?.capacity) ?? 0) < 1) {
          return completion(0.0, nil);
        }

        let sourcePredicate = HKQuery.predicateForObjects(from: s!);

        // todo: enter date patterns
        let datePredicate = HKQuery.predicateForSamples(withStart: start, end: end, options: []);

        //      predicate = [NSPredicate predicateWithFormat:@"metadata.%K != YES", HKMetadataKeyWasUserEntered];
        let manualPredicate = HKQuery.predicateForObjects(withMetadataKey: HKMetadataKeyWasUserEntered, operatorType: .notEqualTo, value: "YES");

        let compound = NSCompoundPredicate(andPredicateWithSubpredicates: [
          sourcePredicate,
          datePredicate,
          manualPredicate
        ]);


        let statOptions = HKStatisticsOptions.cumulativeSum;


        let query = HKStatisticsQuery.init(quantityType:type , quantitySamplePredicate: compound, options: statOptions, completionHandler: { (query, results, error) in

          if (error != nil) {
            return completion(nil, error);
          }

          var total = 0.0;

          // handle if results came back as nil, or sum came back as nil
          guard (results != nil && results?.sumQuantity() != nil) else {
            return completion(total, nil);
          }

          total = results?.sumQuantity()?.doubleValue(for: unit) ?? 0.0;

          return completion(total, nil);
        });

        // execute stats query for step counts by source
        self?.healthStore?.execute(query);
      }
   }
  }

I would really appreciate any form of help, or pointers. Thanks in advance.

↧
↧

How to dynamically disable gestureEnabled in React Navigation?

$
0
0

I'm currently using React Navigation 5.x and I have a modal that swipes downward to close and it has ScrollView on it. The problem is, since the content can be scrolled by gesturing downward, the modal is sometimes accidentally closed. So I want to dynamically disable gestureEnabled to false until onScrollToTop indicates that the ScrollView has reached the top.

<Main.Navigator
    tabBarPosition="none"
    initialRouteName="Main"
    screenOptions={{
        headerShown: false,
        gestureEnabled: true,
        gestureResponseDistance: {
            horizontal: width,
            vertical: height,
        },
    }}
    mode="modal"
    headerMode="none">
 // screens
</Main.Navigator>

How do I pass props to screenOptions to disable gestureEnabled dynamically? Or is there a better way of resolving this?

↧

Issue with rotating image while saving in React Native

$
0
0

Actual Behaviour :

I am supposed to implement signature pad in landscape-right mode along with a timestamp of signature drawn. Then take a screenshot of the view, and save it in document directory (iOS) or external directory (Android) in portrait mode by rotating it. I was successful in implementing signature screen in landscape-right mode using transform: [{rotate: '90deg"}] css property, and react-native-signature-capture, save the captured screenshot of signature along with the timestamp of signature drawn in local directory using react-native-view-shot and convert it into base64 format using react-native-fs.

But the saved screenshot is not in portrait mode and I'm trying to rotate the image while saving it in document directory (iOS) or external directory (Android) without using any modules. I also tried rotating the image while saving it using canvas context API but could not find way to access canvas in react-native to rotate image while saving it as canvas is HTML DOM related.

Expected Behaviour :

I'm supposed to save the signature drawn along with timestamp in document directory (iOS) or external directory (Android) in portrait mode as shown in below screenshot.

Additional Resources :

Code :

render() {
  return (
    <View
    style={{
      flex: 1,
      flexDirection: 'row',
      overflow: "hidden",
    }}>
    <StatusBar hidden={true} />
    <View
      style={{
        flex: 0.8,
        flexDirection: 'row-reverse',
        marginVertical: width / 18,
        overflow: "hidden",
      }}>
      <ViewShot
        ref="viewShot"
        style={[styles.viewShot, { transform: [{ rotate: this.state.bool && '90deg' }] }]}>
        {/* options={{ width: height, height: width }}> */}
        <SignatureCapture
          style={styles.signature}
          ref={sign => (this.signComponent = sign)}
          onSaveEvent={this._onSaveEvent}
          onDragEvent={this._onDragEvent}
          saveImageFileInExtStorage={true}
          showNativeButtons={false}
          showTitleLabel={false}
          showBorder={false}
          viewMode={'portrait'}
          square={true}
          backgroundColor={"white"}
          maxSize={800}
          rotateClockwise={!!true}
        />
        <View
          ref="timeRef"
          style={{
            width: width / 10,
            height: width / 3,
            justifyContent: 'flex-end',
            flexDirection: 'row-reverse',
          }}>
          <View
            style={{
              width: width / 1.8,
              height: width / 1.8,
              transform: [{ rotate: '-90deg' }],
              overflow: "hidden",
              paddingLeft: width / 18,
              paddingTop: width / 25
            }}>
            <Text style={styles.time}>{this.state.data}</Text>
          </View>
        </View>
      </ViewShot>
      <Image
        ref="imageRef"
        source={{ uri: this.state.imageUri }}
        style={{ transform: [{ rotate: '90deg' }] }}
      />
    </View>
    <View
      style={{
        flex: 0.2,
        alignItems: 'center',
        justifyContent: 'space-around',
        flexDirection: 'column',
        overflow: "hidden",
        backgroundColor: Colors.white,
      }}>
      <View
        style={{
          backgroundColor: Colors.darkGreen,
          width: width / 2,
          justifyContent: 'center',
          alignItems: 'center',
          paddingRight: width / 25,
          paddingVertical: width / 37.5,
          transform: [{ rotate: '-90deg' }],
          overflow: "hidden",
        }}>
        <TouchableOpacity
          hitSlop={{ top: 30, left: 50, right: 50, bottom: 30 }}
          onPress={() => {
            this.saveSign();
          }}>
          <Text style={{ fontSize: width / 18, color: Colors.white }}>Submit </Text>
        </TouchableOpacity>
      </View>
      <View
        style={{
          backgroundColor: '#5476ab',
          width: width / 2,
          justifyContent: 'center',
          alignItems: 'center',
          paddingVertical: width / 37.5,
          transform: [{ rotate: '-90deg' }],
          overflow: "hidden",
        }}>
        <TouchableOpacity
          hitSlop={{ top: 30, left: 50, right: 50, bottom: 30 }}
          onPress={() => {
            this.resetSign();
          }}>
          <Text style={{ fontSize: width / 18, color: Colors.white }}>Clear</Text>
        </TouchableOpacity>
      </View>
      <View
        style={{
          backgroundColor: '#73c5de',
          width: width / 2,
          justifyContent: 'center',
          alignItems: 'center',
          paddingVertical: 10,
          transform: [{ rotate: '-90deg' }],
        }}>
        <TouchableOpacity
          hitSlop={{ top: 30, left: 50, right: 50, bottom: 30 }}
          onPress={() => {
            this.onCancel();
          }}>
          <Text style={{ fontSize: width / 18, color: Colors.white }}>Cancel</Text>
        </TouchableOpacity>
      </View>
    </View>
  </View>


 );
}

_onSaveEvent(result) {

    this.setState({ signature: result.pathName, 
                    markResult: result.encoded });
  }

 _onDragEvent() {

    this.setState({ dragged: true });
  }

saveSign() {

    if (this.state.dragged === true) {
      this.setState({ bool: true });
      this.refs.viewShot.capture().then(uri => {
        this.setState({ imageUri: uri });
        console.log("uri123", uri);
         RNFS.readFile(this.state.imageUri, 
          'base64').then(image => {
          console.log("image123", image);
          this.setState({ sign: image }, () => {
            this.ChangeOrientation();
          });
        });
       });
      } else {
      Alert.alert('NALG', 'Please sign the signature 
      pad to submit');
      }

 ChangeOrientation() {

    this.props.getSignature(this.state.sign);
    this.props.setModalVisible(!this.props.modalVisible);
  }

Screenshot of Actual Behaviour :

enter image description here

Screenshot of Expected Behaviour :

enter image description here

Environment:

react-native : 0.61.1

react-native-view-shot : ^3.0.2

react-native-signature-capture : ^0.4.10

react-native-fs : ^2.16.2

↧

Xcode getting iOS development signing certificate and no account build error

$
0
0

While trying to build my react-native app it is failing with errors:

Error starts at: appname_rnative_app_Test 3 issues

1) No account for team "johndoecompany@gmail.com". Add a new account in the Accounts preference pane or verify that your accounts have valid credentials

2) No signing certificate "iOS Development" found: No "iOS Development" signing certificate matching team ID "johndoecompany@gmail.com" with a private key was found.

3) Code signing is required for product type 'Unit Test Bundle' in SDK 'iOS 13.2'

I've made sure in the Apple Developer portal under:

  1. Certificates - Generate APS and APNS certificates along with Development and Distribution certificates
  2. Identifiers - Have my app bundle id registered
  3. Devices - registered physical iPhone XR device
  4. Profiles - Generated both Development and App Store provisioning certificates

MacBook pro - Logged in with my personal apple id Xcode - Have added both personal and johndoecompany@gmail.com apple id in account

When I am building the app it fails with the above 2 errors, please help me resolve it I've been stuck on this issue since a week.

↧
Viewing all 16907 articles
Browse latest View live


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