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

React Native Share Extension - Access to AsyncStorage?

$
0
0

I am working on an application in react native, and was taking a look at some tutorials for creating a 'share extension' within the app. I see on npm react-native-share-extension how to create the extension within the project in xcode, and create a new component with a second AppRegistry (shown from npm example).

//index.ios.js 
import React from 'react'
import { AppRegistry } from 'react-native'

import App from './app.ios'
import Share from './share.ios'

AppRegistry.registerComponent('Sample1', () => App)
AppRegistry.registerComponent('MyShareEx', () => Share)

Does anyone know if the share component would have access to the data stored by the main app in AsyncStorage? (i.e my login token)

Thanks!


Entry, ":CFBundleIdentifier", Does Not Exist. bad path

$
0
0

I had an existing project and decided to built it on ios for the first time. I have configured every package,did pod install etc. Here comes the problem In xCode the build succeeds,but the app won't start on the emulator. Running react-native run-ios throws me this error:

▸ Build Succeeded
info Installing "/Users/bojke/Library/Developer/Xcode/DerivedData/MyApp-ehofomooqvepclgblnmnmzitfpao/Build/Products/Debug-iphonesimulator/React/MyApp.app"
An error was encountered processing the command (domain=NSPOSIXErrorDomain, code=2):
Failed to install the requested application
An application bundle was not found at the provided path.
Provide a valid path to the desired application bundle.
Print: Entry, ":CFBundleIdentifier", Does Not Exist
error Command failed: /usr/libexec/PlistBuddy -c Print:CFBundleIdentifier /Users/bojke/Library/Developer/Xcode/DerivedData/Zakazi-ehofomooqvepclgblnmnmzitfpao/Build/Products/Debug-iphonesimulator/React/Zakazi.app/Info.plist
Print: Entry, ":CFBundleIdentifier", Does Not Exist

I know there is a bunch of issues with the same error, but nothing helped. I tried: - deleting build folder and cd ios && pod install - changing the Derived paths in file>preferences>advanced - react-native start --reset-cache - react-native upgrade - killing all processes on port 8081

What I have noticed that noone had the extra /React/ in the path!

If I delete the /React/ and run the failed commmand it returns the Bundle Indentifier

System:
    OS: macOS 10.15.3
    CPU: (4) x64 Intel(R) Core(TM) i5-4278U CPU @ 2.60GHz
    Memory: 142.41 MB / 8.00 GB
    Shell: 5.7.1 - /bin/zsh
  Binaries:
    Node: 13.8.0 - /usr/local/bin/node
    Yarn: 1.22.0 - /usr/local/bin/yarn
    npm: 6.13.7 - /usr/local/bin/npm
    Watchman: 4.9.0 - /usr/local/bin/watchman
  SDKs:
    iOS SDK:
      Platforms: iOS 13.2, DriverKit 19.0, macOS 10.15, tvOS 13.2, watchOS 6.1
  IDEs:
    Android Studio: 3.5 AI-191.8026.42.35.6010548
    Xcode: 11.3.1/11C504 - /usr/bin/xcodebuild
  npmPackages:
    react: 16.9.0 => 16.9.0 
    react-native: 0.61.5 => 0.61.5 
  npmGlobalPackages:
    react-native-cli: 2.0.1

Xcode Signing Errors

$
0
0

I have a react native project at school under my friend's account. I downloaded it to google drive and opened the Xcode file to run it, (taking care of the signing under my account) but its saying:

"no account for team "******" add a new account in the Account preferences pane or verify that your accounts have valid credentials."

I'm also receiving this error: No signing certificate for "IOS development" found: no signing certificate matching team ID "*****"

the ID it's listing isn't the same as mine.. do I have to somehow use my friend's ID to run this project? I've gone through a whole page of stack overflow questions. Do I need to go to school and download the certificate somehow?

React Native - Disable Password AutoFill Option on iOS Keyboard

$
0
0

In React Native, how do you disable or prevent the keyboard from displaying the Password Autofill accessory view option? There doesn't seem to be an property for TextInput that handles disabling this option. React Native TextInput Documentation. I am also using Expo on top of React Native.

Password AutoFill was introduced in iOS 11

Image of Password AutoFill Accessory view option

Here is a post that has a solution for disabling the password autofill accessory, but how can we achieve this using React Native?

iOS 11 disable password autofill accessory view option?

Avoid status bar overlap on all screens

React Native TextInput setState() issue

$
0
0

I am having an issue with React Native's this.setState() within a TextInput's onChangeText. I am trying to display the content of the TextInput in the Text tag below it. However, it displays nothing -- the setState() call never changes this.state.searchtext. I also get no errors. Thank you in advance for your help! Here is my code:

 export default class ShowScreen extends Component {
constructor(props) {
    super(props);
    this.state = {
        searchtext: ""
    };
}
render() {
    var thisscreen = (
        <View>
            <ScrollView
                horizontal={true}
                showsHorizontalScrollIndicator={false}
                pagingEnabled={true}
            >
                <View
                    style={{
                        flex: 1,
                        height: totalheight,
                        justifyContent: "space-around",
                        alignItems: "center",
                        width: totalwidth,
                        backgroundColor: "#FF0000"
                    }}
                >
                    <TextInput
                        style={{ height: 80, fontSize: 20 }}
                        placeholder="placeholder"
                        value={this.state.searchtext}
                        onChangeText={searchtext =>
                            this.setState({ searchtext })
                        }
                        ref={input => {
                            this.textInput = input;
                        }}
                        returnKeyType="go"
                    />
                    <Text>{this.state.searchtext}</Text>
                </View>
            </ScrollView>
        </View>
    );
    return thisscreen;
}
}

The key isInternetReachable is always returning false for a minute in iOS whenever the app comes to foreground from background in react-native

$
0
0

Platforms

This issue is related to iOS.

Versions

  • iOS: 12.4.1
  • react-native-netinfo: "^5.5.0"
  • react-native: "0.61.5"
  • react: "16.9.0"

Description

I'm working on implementing network status check in a project with dynamic data and checking for internet reachability whenever an API call is made or the app state changes. My issue is that the key isInternetReachable is always returning false for a minute before returning the correct status whenever app comes to foreground from background even though internet is reachable. The issue is happening on iOS real device and everything is working fine on iOS simulator and android real device. Can someone help me please. Thanks in advance.

Reproducible Demo

let state;
componentDidMount() {
        // Adding AppState event listener
        AppState.addEventListener('change', this._handleAppStateChange);
        // Adding NetInfo event listener
        this._subscription = NetInfo.addEventListener(
            this._handleConnectionInfoChange,
        );
    }
 componentWillUnmount() {
        // Removing AppState event listener
        AppState.removeEventListener('change', this._handleAppStateChange);
        // Removing NetInfo event listener
        this._subscription && this._subscription();
    }
_handleAppStateChange = async nextAppState => {
        if (this.state.appState.match(/inactive|background/) && nextAppState === 'active') {
            state = await NetInfo.fetch();
            });
        }
        if (this.state.appState.match(/active|inactive/) && nextAppState === 'background') {
            state = await NetInfo.fetch();
            });
        }
        if (this.state.appState.match(/active|background/) && nextAppState === 'inactive') {
            state = await NetInfo.fetch();
            });
        }
        this.setState({ appState: nextAppState });
    };
 getJobs = async (index) => {
        // fetching status of internet connection
        state = await NetInfo.fetch();
            if (state.isInternetReachable === false) {
                Alert.alert(Constants.k_APP_NAME, Constants.k_OFFLINE_TEXT);
            } else {
                this.props.callService(item, false);
            }
        }
    }

Restrict availability in App store with iPhone Models

$
0
0

we are launching a React Native app on App Store. We found the app is little slow on older devices. We are thinking to target new models first and solve issues for older models later. Can we restrict release to iPhone model rather than iOS Version?


iOS: BrightCove native player throwing `kBCOVPlaybackSessionLifecycleEventError` playing same video on 2nd time

$
0
0

I want to resume video second time from the same time interval from which I left last time. But when I'm opening player for the second time, it either take longer time than the usual or (and mostly) it throws kBCOVPlaybackSessionLifecycleEventError Not sure what and why it's happening. Following is my pseude code to resume the video. Can anyone please help on this? In the native docs also, there is not much info is mentioned which can be of help. So do let me know if anyone has input on this one?

Here is the link for brightcove-ios-native SDK

func seekToTimeWithSeconds(seconds:Double) {
    let seekToTime = CMTimeMakeWithSeconds(seconds, preferredTimescale: 60000)
    playbackController?.seek(to: seekToTime, completionHandler: { [weak self] (finished: Bool) in
        self?.playbackController.play()
    })
}

expo.io's BackgroundFetch is not running the defined task

$
0
0

I am currently developing an app for iOS with expo sdk-version 32. I have to call a REST service periodically from my app. In order to do that I tried to utilize the new BackgroundFetch API.

Here is my Code:

const BACKGROUND_LOCATION_SENDING_TASK = "BACKGROUND_LOCATION_SENDING_TASK";

async function initBackgroundLocationSending() {
    console.log("initBackgroundLocationSending()");

    TaskManager.defineTask(BACKGROUND_LOCATION_SENDING_TASK, () => {

        // this console.log does never get called ... 
        console.log("BACKGROUND_LOCATION_SENDING_TASK");

        // i will implement real fetch logic here when i found out how to get this function called.
        return BackgroundFetch.Result.NewData;
    });

    console.log("is task registered ... ");
    let isRegistered = await TaskManager.isTaskRegisteredAsync(BACKGROUND_LOCATION_SENDING_TASK);
    console.log("isRegistered: ", isRegistered);

    if(isRegistered) {
        console.log("unregister task ...");
        await BackgroundFetch.unregisterTaskAsync(BACKGROUND_LOCATION_SENDING_TASK);
        console.log("Done");
    }

    console.log("is task registered ... ");
    isRegistered = await TaskManager.isTaskRegisteredAsync(BACKGROUND_LOCATION_SENDING_TASK);
    console.log("isRegistered: ", isRegistered);

    console.log("register task ...");
    await BackgroundFetch.registerTaskAsync(BACKGROUND_LOCATION_SENDING_TASK);
    console.log("OK");


    console.log("is task registered ... ");
    isRegistered = await TaskManager.isTaskRegisteredAsync(BACKGROUND_LOCATION_SENDING_TASK);
    console.log("isRegistered: ", isRegistered);

    console.log("set minimum interval ...");
    await BackgroundFetch.setMinimumIntervalAsync(60);
    console.log("OK");

    console.log("get status ... ");
    const status = await BackgroundFetch.getStatusAsync();
    console.log("status: ", status);
}

Console output from calling the function from within App.js:

: initBackgroundLocationSending()
: is task registered ...
: isRegistered:  true
: unregister task ...
: OK
: is task registered ...
: isRegistered:  false
: register task ...
: OK
: is task registered ...
: isRegistered:  true
: set minimum interval ...
: OK
: get status ...
: status:  3

From expo's background-fetch documentation I understand that status: 3 means BackgroundFetch.Status.Available.

the iOS section from my app.json:

...
"ios": {
  "supportsTablet": true,
  "bundleIdentifier": "xxx-yyy-zzz",
  "infoPlist": {
    "UIBackgroundModes": [
      "location",
      "fetch"
    ],
    "NSLocationWhenInUseUsageDescription": "... (replaced)",
    "NSLocationAlwaysAndWhenInUseUsageDescription": "... (replaced)",
    "NSLocationAlwaysUsageDescription": "... (replaced)"
  }
},
...

My testing device is an IPhone 6s with iOS 12.1.3.

What am I missing? Why does it not run the task at all even not after some minutes?

btw: I use expo's background location without any problems

No known class method for selector 'labelColor' - react-native-image-crop-picker - for react-native iOS

$
0
0

I am using react-native-image-crop-picker library within react-native application Version details

react-native version: 59.10
 react-native-image-crop-picker: 0.25.3
 xcode: 10.1

While execution of code I am getting the error QBImagePicker/QBAssetsViewController.m:198:31: No known class method for selector 'labelColor'

195    // Info label
196    UIColor *labelColor = [UIColor blackColor];
197    if (@available(iOS 13.0, *)) {
198        labelColor = [UIColor labelColor];
199    }

I have tried to upgrade library version but issue is still there. can anyone please help

Thank you in advance

How do i open an S3 link to share to Instagram?

$
0
0

I'm using React Native to create an iOS app. In the code below, I can easily access items in my gallery to open Instagram and share as a Story or on the Feed. However i would like to share a uri to an S3 video as follows:

import React from 'react'
import { Share, Linking ....} from 'react-native'

//Click button and run function
testShareInsta = async () => {
     const uri = "https://s3-dev.s3-us-west-1.amazonaws.com/video/myvideo";
     let encodedURL = encodeURIComponent(uri);  
     let instagramURL = 'instagram://library?AssetPath=${encodedURL}';
     return Linking.openURL(instagramURL);
  }

What's wrong here?

console.error: "react-native-maps" AirGoogleMaps dir must be added to your xCode project

$
0
0

console.error: "react-native-maps" AirGoogleMaps dir must be added to your xCode project

I got this error when I am trying to test the example in react-native-maps module.

Github: https://github.com/airbnb/react-native-maps/tree/master/example

It is obvious that I should add the dir the to my Xcode project but I don't know how to add them.

May I have an example of adding dir to a Xcode project?

image of error

How to get current country of Device in React Native (iOS and Android)?

$
0
0

I am trying to get current country of device in but didn't find anything. Is there something to do so in React Native? I tried using react-native-device-info but it is also not supporting but in previous version it can be get by getDeviceCountry(). Now for the latest version it is showing error:

TypeError: _reactNativeDeviceInfo.default.getDeviceCountry is not a function. (In '_reactNativeDeviceInfo.default.getDeviceCountry()', '_reactNativeDeviceInfo.default.getDeviceCountry' is undefined)

navigator.geolocation.watchPosition not working correctly on ios device

$
0
0

I have a strange behavior and can not find a solution. In my React Native application I'm using the navigator.geolocation to determine the current position. My application is almost identical as the example in Facebook's Geolocation Code.

In the simulator my application works perfectly, but when I deploy it to my iphone the returning position (by getCurrentPosition and watchPosition) is not correctly. For example speed and heading is -1, accuracy is 65. Longitude and latitude seem to be valid, but not my real position (is in another country). It does not matter whether I deploy the application via debug or release to the iphone, it always reacts same.

But if I start for example TomTom and put this application in the background, and then start my GeolocationExample application, everything works as it should.

My application I have created as follows:

react-native init GeolocationExample

And then I replaced the file index.ios.js with this code.

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

export default class GeolocationExample extends React.Component {
  state = {
    initialPosition: 'unknown',
    lastPosition: 'unknown',
  };

  watchID: ?number = null;

  componentDidMount() {
    navigator.geolocation.getCurrentPosition(
      (position) => {
        var initialPosition = JSON.stringify(position);
        this.setState({initialPosition});
      },
      (error) => alert(JSON.stringify(error)),
      {enableHighAccuracy: true, timeout: 20000, maximumAge: 1000}
    );
    this.watchID = navigator.geolocation.watchPosition((position) => {
      var lastPosition = JSON.stringify(position);
      this.setState({lastPosition});
    });
  }

  componentWillUnmount() {
    navigator.geolocation.clearWatch(this.watchID);
  }

  render() {
    return (
      <View style={styles.main}>
        <Text>
          <Text style={styles.title}>Initial position: </Text>
          {this.state.initialPosition}
        </Text>
        <Text>
          <Text style={styles.title}>Current position: </Text>
          {this.state.lastPosition}
        </Text>
      </View>
    );
  }
}

var styles = StyleSheet.create({
  main: {
    margin: 30
  },
  title: {
    fontWeight: '500',
  },
});

AppRegistry.registerComponent('GeolocationExample', () => GeolocationExample);

Include react-vr in react-native

$
0
0

I would like to know if it's possible to integrate a react vr tour inside an Android and/or iOS app developed with react native. If so, how I can do it?

This is just an idea but I haven't found a real solution on-line.

Thanks for the attention.

(I'm Italian. Excuse me if you do not understand my English)

How to properly dismiss Multiple Modals(Modal inside Modal) in React Native

$
0
0

It turns out that in React Native there's no proper way to show Modal on top of the Modal.

There's some hack how to achieve this and that's exactly the way how I implemented it in my project. But there's another issue: when I dismiss parent modal app got frozen(on IOS, didn't check Android, but I need both platforms to be working) and parent modal remain opened and you have to force close the app to unblock UI

Modal inside Modal dismiss issue

Code:

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

class MultipleModal extends Component {
 state = {
   parentModalVisible: false,
   childModalVisible: false,
 };

 closeOpenModal = (parentModalVisible) => {
   this.setState({
     parentModalVisible,
     childModalVisible: parentModalVisible,
   });
 };

 renderModals() {
   const { parentModalVisible, childModalVisible } = this.state;
   return (
     <Modal
       visible={parentModalVisible}
       transparent={false}
       animationType={'none'}
       onRequestClose={() => this.closeOpenModal(false)}
     >
       <View style={{ flex: 1, backgroundColor: 'red' }} />
       <Modal
         visible={childModalVisible}
         transparent={false}
         animationType={'none'}
         onRequestClose={() => this.closeOpenModal(false)}
       >
         <View style={{ flex: 1, backgroundColor: 'green' }}>
           <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
             <TouchableHighlight
               style={{ width: 100, height: 40, justifyContent: 'center', alignItems: 'center', backgroundColor: 'lightblue' }}
               onPress={() => this.closeOpenModal(false)}
             >
               <Text>Close Modal</Text>
             </TouchableHighlight>
           </View>
         </View>
       </Modal>
     </Modal>
   );
 }

 render() {
   return (
     <View style={{ flex: 1 }}>
       <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
         <TouchableHighlight
           style={{ width: 100, height: 40, justifyContent: 'center', alignItems: 'center', backgroundColor: 'lightblue' }}
           onPress={() => this.closeOpenModal(true)}
         >
           <Text>Open Modal</Text>
         </TouchableHighlight>
       </View>
       {this.renderModals()}
     </View>
   );
 }
}

export default MultipleModal;


The question is what is proper way to dismiss multiple modals? Because currently to avoid this issue I have to close modals asynchronously, first child and then parent which a bit painful and adds complexity to the code and possible issues:

  closeModal = () => {
    // Dismiss child
    this.setState({ childModalVisible: false }, () => {
      // Dismiss parent, but add requestAnimationFrame to prevent app from being frozen
      requestAnimationFrame(() => {
        this.setState({ parentModalVisible: false });
      });
    });
  };

React Native - Sliding up Panel does not work on android

$
0
0

Does Anyone knows why the panel is not showing on android when I click on the button? I'm using https://www.npmjs.com/package/rn-sliding-up-panel btw. Please feel free to tell me, if you have any other recommended sliding panel library.

    ...
    <Button title="Show panel" onPress={() => _panel.show(400)} />
    ...
    <SlidingUpPanel
              style={{borderTopLeftRadius: 10}}
              ref={c => (_panel = c)}>
              <View
                style={{
                  flex: 1,
                  backgroundColor: 'white',
                  alignItems: 'center',
                  borderTopRightRadius: 18,
                  borderTopLeftRadius: 18,
                }}>
                <Text>Header</Text>
                <Text>Content</Text>
                <Button title="Hide" onPress={() => _panel.hide()} />
              </View>
    </SlidingUpPanel>

enter image description here

unable to open file (in target "React" in project "Pods") (in target 'React')

$
0
0

I have one reactNative project and i am trying to run in latest xcode 10.1.But its throwing two error while i building.

error :

Users/ios/Pods/Target Support Files/React/React.xcconfig: unable to open file (in target "React" in project "Pods") (in target 'React')

Users/ios/Pods/Target Support Files/React/React.xcconfig: unable to open file (in target "React" in project "Pods") (in target 'React')

my pod file is like below :

 source 'https://github.com/CocoaPods/Specs.git'
platform :ios, '9.0'

EXPO_CPP_HEADER_DIR = 'ExpoKit'

target 'commonalityre' do
  pod 'ExpoKit',
    :git => "http://github.com/expo/expo.git",
    :tag => "ios/2.6.8",
    :subspecs => [
      "Core",
      "CPP",
      "GL"
    ],
    :inhibit_warnings => true

  pod 'React',
    :path => "../node_modules/react-native",
    :inhibit_warnings => true,
    :subspecs => [
      "Core",
      "ART",
      "RCTActionSheet",
      "RCTAnimation",
      "RCTCameraRoll",
      "RCTGeolocation",
      "RCTImage",
      "RCTNetwork",
      "RCTPushNotification",
      "RCTText",
      "RCTVibration",
      "RCTWebSocket",
      "DevSupport",
      "CxxBridge"
    ]
  pod 'yoga',
    :path => "../node_modules/react-native/ReactCommon/yoga",
    :inhibit_warnings => true

Not sure how can i solve this. I tried deleting derived data, and clean, nothing help. Still i am getting this error.

Thanks

Sharing a video via a PHAsset

$
0
0

Background:

I have an app written in react-native that uses the react-native-share package. I've forked this package as there is an issue where a downloaded image or video won't share from a placeholder asset (PHAsset) URL (e.g. ph://[media-id])

I've had some partial success with the code below and Images now work. Videos are proving a little more tricky. I can take the ph:// URL and get the asset which results in a file:// URL that works ONLY when sharing via airdrop. The URL resolves and I get the MP4 file on my desktop...great!

The Problem:

However, if I try and share the same file:// URL to a message or email I just see the link itself.

Possible solution:

I'm assuming I need to resolve that video asset to an NSData object in the Obj-c and then send the file itself back for the share component to handle (like the image one does) but I'm not too great with Obj-C so would appreciate some help! For videos, the file is always an mp4 file.

Here's my code: (I'm passing the ph:// URL to the native side...)

...
if([URL.scheme.lowercaseString isEqualToString:@"ph"]) {
    NSString *assetIdentifier = [urlsArray[i] stringByReplacingOccurrencesOfString: @"ph://" withString: @""];
    PHFetchResult *fetchResult = [PHAssetCollection fetchAssetCollectionsWithLocalIdentifiers: @[assetIdentifier] options:nil];
    PHAsset *asset = fetchResult.firstObject;

    PHImageRequestOptions *options = [[PHImageRequestOptions alloc] init];
    options.synchronous = YES;
    options.version = PHImageRequestOptionsVersionCurrent;
    options.deliveryMode = PHImageRequestOptionsDeliveryModeOpportunistic;
    options.resizeMode = PHImageRequestOptionsResizeModeNone;

    PHVideoRequestOptions *options2 = [[PHVideoRequestOptions alloc] init];
    options2.networkAccessAllowed = YES;
    options2.deliveryMode = PHVideoRequestOptionsDeliveryModeHighQualityFormat;
    options2.version = PHVideoRequestOptionsVersionCurrent;

    NSString __block *url = @"";

    if (asset){
        switch(asset.mediaType) {
            case PHAssetMediaTypeVideo: {
                //*** THIS IS THE PROBLEMATIC AREA ***
                [[PHImageManager defaultManager] requestAVAssetForVideo:asset options:options2 resultHandler:^(AVAsset * _Nullable asset, AVAudioMix * _Nullable audioMix, NSDictionary * _Nullable info) {
                    AVURLAsset *urlAsset = (AVURLAsset*)asset;

                    url = [[urlAsset URL] absoluteString];

                    [items addObject: url];  //items is passed over to the share handler
                    dispatch_semaphore_signal(semaphore);   //added to counter-act the fact requestAVAssetForVideo is asynchronous   
                }];
            break;
            }
            case PHAssetMediaTypeImage: {
                //*** THIS SHARES IMAGES AS EXPECTED ***
                [[PHImageManager defaultManager] requestImageDataForAsset:asset options:options resultHandler:^(NSData * _Nullable imageData, NSString * _Nullable dataUTI, UIImageOrientation orientation, NSDictionary * _Nullable info)
                {
                    [items addObject:imageData];   //items is passed over to the share handler
                    dispatch_semaphore_signal(semaphore);    //added to counter-act the fact requestAVAssetForVideo is asynchronous
                }];
                break;
            }
            default: {
                RCTLogError(@"Asset type can't be shared");
                return;
            }
        }     
    }
} 
...
Viewing all 16907 articles
Browse latest View live


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