Skip to content

Instantly share code, notes, and snippets.

@gopalakrishnan-subramani
Last active December 28, 2020 05:24
Show Gist options
  • Save gopalakrishnan-subramani/f2b39680521a135a780085d628317ee9 to your computer and use it in GitHub Desktop.
Save gopalakrishnan-subramani/f2b39680521a135a780085d628317ee9 to your computer and use it in GitHub Desktop.
React Native
import React, { Component, PropTypes } from 'react'
import {
CameraRoll,
Image,
ScrollView,
StyleSheet,
TouchableHighlight,
View,
} from 'react-native';
class CameraRollView extends Component {
static navigationOptions = {
title: 'Camera Roll'
}
constructor(props) {
super(props)
var controls = props.controls
this.state = {
images: [],
selected: '',
fetchParams: { first: 25, assetType: 'Photos' },
//groupTypes: 'SavedPhotos',
}
this._storeImages = this._storeImages.bind(this)
this._logImageError = this._logImageError.bind(this)
this._selectImage = this._selectImage.bind(this)
}
componentDidMount() {
// get photos from camera roll
//CameraRoll.getPhotos(this.state.fetchParams, this._storeImages, this._logImageError);
CameraRoll.getPhotos(this.state.fetchParams)
.then(this._storeImages)
.catch(this._logImageError);
}
// callback which processes received images from camera roll and stores them in an array
_storeImages(data) {
const assets = data.edges;
const images = assets.map( asset => asset.node.image );
this.setState({
images: images,
});
}
_logImageError(err) {
console.log(err);
}
_selectImage(uri) {
// define whatever you want to happen when an image is selected here
this.setState({
selected: uri,
});
console.log('Selected image: ', uri);
}
render() {
return (
<View style={{flex: 1, backgroundColor: 'white'}}>
<ScrollView style={styles.container}>
<View style={styles.imageGrid}>
{ this.state.images.map( (image, i) => {
return (
<TouchableHighlight onPress={() => this._selectImage(image.uri) } key={i}>
<Image style={styles.image} source={ { uri: image.uri } } />
</TouchableHighlight>
);
})}
</View>
</ScrollView>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#F5FCFF',
},
imageGrid: {
flexDirection: 'row',
flexWrap: 'wrap',
justifyContent: 'center'
},
image: {
width: 100,
height: 100,
margin: 10,
},
});
export default CameraRollView

Get Started

react-native init SpecApp
cd SpecApp

react-native run-ios

react-native run-android

Log Commands

react-native log-ios

react-native log-android

iOS Log When not working with log-ios option

log stream --predicate '(processImagePath contains "yourAppName") and senderImageUUID == processImageUUID'

or Use script node.js, needs
npm install moment


Simulator Commands

iOS

  - Cmd + R to reload
  - Cmd + D to Dev Menu

Android

  - Double Tab R to reload
  - Cmd + M to Dev Menu

Debug

https://github.com/facebook/react-devtools/tree/master/packages/react-devtools

  npm install -g react-devtools
  react-devtools

  
  By default DevTools listen to port 8097 on localhost.

  If not running on Simulator, you may do this, not tested
  
  adb reverse tcp:8097 tcp:8097

Resize Use Emulator Edge to increase size

VS Code

Add Extension 'React Native Tools'

The files related to vscode stored in .vscode/.react, ignore in .gitignore

Icons

https://github.com/oblador/react-native-vector-icons

npm install react-native-vector-icons

react-native link

  import Icon from 'react-native-vector-icons/FontAwesome';
  const myButton = (
    <Icon.Button name="facebook" backgroundColor="#3b5998" onPress={this.loginWithFacebook}>
      Login with Facebook
    </Icon.Button>
  );

  const customTextButton = (
    <Icon.Button name="facebook" backgroundColor="#3b5998">
      <Text style={{fontFamily: 'Arial', fontSize: 15}}>Login with Facebook</Text>
    </Icon.Button>
  );

File System

No Specific Permission Needed

npm install react-native-fs

react-native link react-native-fs

CameraRollView

Android, Just use it

iOS, Need to Link RCTCameraRoll to Project https://facebook.github.io/react-native/docs/linking-libraries-ios

Ensure adding libRCTCameraRoll.a to Main PRoject, 'Build Phases' => 'Link Libraries' section

iOS need permissions

  <key>NSPhotoLibraryUsageDescription</key>
   <string>Camera Roll Preview </string>

for iOS 11.0, add also

	<key>NSPhotoLibraryAddUsageDescription</key>
	<string>Demo purpose</string>

React Native Fetch Blob

A faster fetch library, for downloading images and large files https://github.com/joltup/rn-fetch-blob

npm install rn-fetch-blob

react-native link

Needs Android Permission for sd card write and read Add to AndroidManifest.xml

   <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />                                               
   <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />                                              
    <uses-permission android:name="android.permission.DOWNLOAD_WITHOUT_NOTIFICATION" />

Camera

	npm install react-native-camera
	react-native link react-native-camera

Android.manifest file permission

	<uses-permission android:name="android.permission.RECORD_AUDIO"/>
	<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
	<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

ios pInfo

<key>NSCameraUsageDescription</key>
<string>Your message to user when the camera is accessed for the first time</string>

<!-- Include this only if you are planning to use the camera roll -->
<key>NSPhotoLibraryUsageDescription</key>
<string>Your message to user when the photo library is accessed for the first time</string>

<!-- Include this only if you are planning to use the microphone for video recording -->
<key>NSMicrophoneUsageDescription</key>
<string>Your message to user when the microphone is accessed for the first time</string>


iOS 11

<!-- Include this only if you are planning to use the camera roll -->
<key>NSPhotoLibraryAddUsageDescription</key>
<string>Your message to user when the photo library is accessed for the first time</string>

import React, {Component} from "react";
import {View, Text, Button, Alert} from "react-native";
import {Platform} from "react-native";
var RNFS = require('react-native-fs');
export default class FileSys extends Component {
static navigationOptions = {
title: 'File System'
}
constructor(props) {
super(props);
this.state = {
content: ''
}
}
componentDidMount() {
}
readFile() {
let docDirectoryPath = Platform.OS == 'ios'? RNFS.MainBundlePath:RNFS.DocumentDirectoryPath;
var path = docDirectoryPath + '/test.txt';
RNFS.readFile(path, 'utf8')
.then((contents) => {
// log the file contents
console.log(contents);
Alert.alert(contents);
})
.catch (error => {
Alert.alert("could not read file");
console.log(error);
});
}
checkFile() {
let docDirectoryPath = Platform.OS == 'ios'? RNFS.MainBundlePath:RNFS.DocumentDirectoryPath;
var path = docDirectoryPath + '/test.txt';
RNFS.stat(path)
.then((statResult) => {
if (statResult.isFile()) {
Alert.alert("File test exist")
}
})
.catch ( error => {
Alert.alert("test file does not exist");
});
}
writeFile() {
// create a path you want to write to
let docDirectoryPath = Platform.OS == 'ios'? RNFS.MainBundlePath:RNFS.DocumentDirectoryPath;
var path = docDirectoryPath + '/test.txt';
// write the file
RNFS.writeFile(path, '{"counter": 1}', 'utf8')
.then((success) => {
console.log('FILE WRITTEN!');
Alert.alert("Written file");
})
.catch((err) => {
Alert.alert("Error could not write file");
console.log(err.message);
});
}
render() {
return (
<View>
<Text>{this.state.url}</Text>
<Button onPress={()=> this.checkFile()}
title="Check File">
</Button>
<Button onPress={()=> this.writeFile()}
title="Write File">
</Button>
<Button onPress={()=> this.readFile()}
title="Read File">
</Button>
</View>
)
}
}
import React from 'react'
import {
View,
Text,
Button,
Image,
ActivityIndicator,
StyleSheet,
Dimensions,
ScrollView,
CameraRoll,
TouchableHighlight,
Platform,
Alert
} from 'react-native'
const APP_ID = 'd09cb415654d703c14a74ad44b1b03a6a60325df2940a70dc236700c9093c15e';
import RNFetchBlob from 'rn-fetch-blob'
const { width, height } = Dimensions.get('window')
let styles
class ImageBrowser extends React.Component {
static navigationOptions = {
title: 'Unsplash Images',
}
state = {
images: [],
loading: true,
page: 1
}
componentDidMount() {
this.fetchPhotos()
}
fetchPhotos = () => {
this.setState({ loading: true })
fetch(`https://api.unsplash.com/photos/?page=${this.state.page}&per_page=30&client_id=${APP_ID}`)
.then(res => res.json())
.then(images => {
this.state.images.push(...images)
console.log('this.state.images: ', this.state.images)
this.setState({ images: this.state.images, loading: false, page: this.state.page + 1 })
})
}
saveToCameraRoll = (image) => {
if (Platform.OS === 'android') {
RNFetchBlob
.config({
fileCache : true,
appendExt : 'jpg'
})
.fetch('GET', image.urls.small)
.then((res) => {
CameraRoll.saveToCameraRoll(res.path())
.then(Alert.alert('Success', 'Photo added to camera roll!'))
.catch(err => console.log('err:', err))
})
} else {
CameraRoll.saveToCameraRoll(image.urls.small)
.then(Alert.alert('Success', 'Photo added to camera roll!'))
}
}
render() {
return (
<View style={{flex: 1}}>
<Text style={styles.title}>Unsplash Images</Text>
{
this.state.loading ? (
<Text style={{ padding: 10, textAlign: 'center' }}>Loading...</Text>
) : (
<Button
onPress={this.fetchPhotos}
title='View More'
/>
)
}
<ScrollView contentContainerStyle={styles.scrollContainer}>
{
this.state.images.map((image, i) => {
return (
<TouchableHighlight
key={i}
onPress={() => this.saveToCameraRoll(image)}
underlayColor='transparent'
>
<Image
style={styles.image}
source={{ uri: image.urls.small }}
/>
</TouchableHighlight>
)
})
}
</ScrollView>
</View>
)
}
}
styles = StyleSheet.create({
scrollContainer: {
flexDirection: 'row',
flexWrap: 'wrap'
},
centerLoader: {
height: height - 100,
width,
justifyContent: 'center',
alignItems: 'center'
},
image: {
width: width / 2, height: width / 2
},
title: {
textAlign: 'center',
padding: 20
}
})
export default ImageBrowser
#!/usr/bin/env node
'use strict';
const moment = require("moment");
const {spawn} = require('child_process');
const yourAppName = 'SpecApp'
const args = [
'stream',
'--predicate', `(processImagePath contains "${yourAppName}") and senderImageUUID == processImageUUID`,
'--style', 'json'
];
const lg = spawn('log', args);
lg.stdout.on('data', data => {
const str = data.toString();
// Assumption: { is always at the end of a line, } at the start of line.
const m = str.match(/\{$[\s\S]+?^\}/mg);
if (m === null) {
return;
}
const all = m.map(str => JSON.parse(str));
all.forEach(({timestamp, eventMessage}) => {
const time = moment(timestamp).format("H:mm:ss");
console.log([time, eventMessage].join(", "));
console.log("\n");
});
});
lg.stderr.on('data', data => {
console.log(`stderr: ${data}`);
});
lg.on('close', code => {
console.log(`child process exited with code ${code}`);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment