본문 바로가기
웹 프론트엔드/React-Native

React-Native : qrcode 스캐너 이용하기

by 번데기 개발자 2020. 7. 19.
반응형

React-Native로 QR코드 인식 카메라 구현해보기

 

 

React-Native로 개발하던중 qrcode를 사용할 일이있어서, 해당 react-native-qrcode-scanner라는 라이브러리를 찾게 되었습니다..

 

외국문서는 많이 있지만 한글로 된 문서는 많이 없는것 같아서 구현하고 테스트하는데 시간이 생각보다 걸리더라구요..

 

아래 방법으로 구현하면 실제로 예제는 구동시킬수 있는것 같아서 간단하게 메모를 해보았습니다. ~

 

 

1. react-native-qrcode-scanner 라이브러리 설치 및 의존성 라이브러리 설치

 

npm install react-native-camera 
npm install react-native-qrcode-scanner
npm install react-native-permissions

// react-native 0.60 버전 이하일때는 링크
react-native link react-native-camera 
react-native link react-native-qrcode-scanner
react-native link react-native-permissions

 

 

2. android 일 때 환경설정

 

  • app/build.gradle 코드 수정
android {
    compileSdkVersion rootProject.ext.compileSdkVersion

    compileOptions {
    ...
    }

    defaultConfig {
        ...
        ...
        // 아래 부분 추가 
        missingDimensionStrategy 'react-native-camera', 'general'
        missingDimensionStrategy 'react-native-camera', 'mlkit'
        // multiDex 에러를 위해 미리 추가해두는 것이 좋음
        multiDexEnabled true
    }

 

 

3. ios 일때 환경 설정

  • ios/info.plist 수정
// 아래 key value 추가
<key>NSCameraUsageDescription</key>
<string>Your message to user when the camera is accessed for the first time</string>
<key>NSMicrophoneUsageDescription</key>
<string>Your message to user when the microsphone is accessed for the first time</string>
<key>NSPhotoLibraryUsageDescription</key>
<string>Your message to user when the photo library is accessed for the first time</string>

 

  • ios/podfile 수정
target 'ReactNativeBarcode' do
  # Permissions (퍼미션 요청을 위한 코드 추가)
  permissions_path = '../node_modules/react-native-permissions/ios'
  pod 'Permission-Camera', :path => "#{permissions_path}/Camera.podspec"

  # Pods for ReactNativeBarcode
  ...
end

 

 

 

실제로 Hooks로 구현한 제 코드입니다.

필요하면 참고해주세요 ~ :)

 

 

import React, {Component, useEffect, useState, useRef} from 'react';
import {
  StyleSheet,
  View,
  Text,
  Linking,
  TouchableOpacity
} from 'react-native';

import { Dimensions } from 'react-native';
const deviceWidth = Dimensions.get('screen').width;
const deviceHeight = Dimensions.get('screen').height;

import QRCodeScanner from 'react-native-qrcode-scanner';

const QRCodeScreen = (props) => {
  const [scan, setScan] = useState(false);
  const [scanResult, setScanResult] = useState(false);
  const [result, setResult] = useState(null);

  const scanner = React.useRef('');

  const onSuccess = (e) => {
    const check = e.data.substring(0, 4);
    console.log('scanned data' + check);

    setResult(e);
    setScan(false);
    setScanResult(true);


    if (check === 'http') {
      Linking
        .openURL(e.data)
        .catch(err => console.error('An error occured', err));

    } else {
      setResult(e);
      setScan(false);
      setScanResult(true);

    }
  };

  const activeQR = () => {
    setScan(true)
  };


  const scanAgain = () => {
    setScan(true);
    setScanResult(false);
  };

  const desccription = 'QR code (abbreviated from Quick Response Code) is the trademark for a type of matrix barcode (or two-dimensional barcode) first designed in 1994 for the automotive industry in Japan. A barcode is a machine-readable optical label that contains information about the item to which it is attached. In practice, QR codes often contain data for a locator, identifier, or tracker that points to a website or application. A QR code uses four standardized encoding modes (numeric, alphanumeric, byte/binary, and kanji) to store data efficiently; extensions may also be used.'


  useEffect(() => {

  }, []);

  return (
    <View style={styles.container}>
      <View>
        {/*<StatusBar barStyle="dark-content" />*/}
        <Text style={styles.textTitle}>Welcome To React-Native QR Code Tutorial !</Text>
        {!scan && !scanResult &&
        <View style={styles.cardView} >
          <Text numberOfLines={8} style={styles.descText}>{desccription}</Text>

          <TouchableOpacity onPress={activeQR} style={styles.buttonTouchable}>
            <Text style={styles.buttonTextStyle}>Click to Scan !</Text>
          </TouchableOpacity>

        </View>
        }

        {scanResult &&
        <Fragment>
          <Text style={styles.textTitle1}>Result !</Text>
          <View style={ScanResult ? styles.scanCardView : styles.cardView}>
            <Text>Type : {result.type}</Text>
            <Text>Result : {result.data}</Text>
            <Text numberOfLines={1}>RawData: {result.rawData}</Text>
            <TouchableOpacity onPress={scanAgain} style={styles.buttonTouchable}>
              <Text style={styles.buttonTextStyle}>Click to Scan again!</Text>
            </TouchableOpacity>

          </View>
        </Fragment>
        }


        {scan &&
        <QRCodeScanner
          reactivate={true}
          showMarker={true}
          ref={(node) => { scanner.current = node }}
          onRead={this.onSuccess}
          topContent={
            <Text style={styles.centerText}>
              Go to <Text style={styles.textBold}>wikipedia.org/wiki/QR_code</Text> on your computer and scan the QR code to test.</Text>
          }
          bottomContent={
            <View>
              <TouchableOpacity style={styles.buttonTouchable} onPress={() => scanner.current.reactivate()}>
                <Text style={styles.buttonTextStyle}>OK. Got it!</Text>
              </TouchableOpacity>

              <TouchableOpacity style={styles.buttonTouchable} onPress={() => setScan(false)}>
                <Text style={styles.buttonTextStyle}>Stop Scan</Text>
              </TouchableOpacity>
            </View>

          }
        />
        }
      </View>
    </View>
  )
};

export default QRCodeScreen;

const styles = StyleSheet.create({
  container: {
    backgroundColor: 'white',
    height: '100%',
    width: '100%',
  },



  scrollViewStyle: {
    flex: 1,
    justifyContent: 'center',
    backgroundColor: '#99003d'
  },

  textTitle: {
    fontWeight: 'bold',
    fontSize: 18,
    textAlign: 'center',
    padding: 16,
    color: 'white'
  },
  textTitle1: {
    fontWeight: 'bold',
    fontSize: 18,
    textAlign: 'center',
    padding: 16,
    color: 'black'
  },
  cardView: {
    width: deviceWidth - 32,
    height: deviceHeight / 2,
    alignSelf: 'center',
    justifyContent: 'flex-start',
    alignItems: 'center',
    borderWidth: 1,
    borderRadius: 2,
    borderColor: '#ddd',
    borderBottomWidth: 0,
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.8,
    shadowRadius: 2,
    elevation: 4,
    marginLeft: 5,
    marginRight: 5,
    marginTop: 10,
    backgroundColor: 'white'
  },
  scanCardView: {
    width: deviceWidth - 32,
    height: deviceHeight / 2,
    alignSelf: 'center',
    justifyContent: 'center',
    alignItems: 'center',
    borderWidth: 1,
    borderRadius: 2,
    borderColor: '#ddd',
    borderBottomWidth: 0,
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.8,
    shadowRadius: 2,
    elevation: 4,
    marginLeft: 5,
    marginRight: 5,
    marginTop: 10,
    backgroundColor: 'white'
  },
  buttonScan: {
    width: 42,

  },
  descText: {
    padding: 16,
    textAlign: 'justify',
    fontSize: 16
  },


  highlight: {
    fontWeight: '700',
  },

  centerText: {
    flex: 1,
    fontSize: 18,
    padding: 32,
    color: '#777',
  },
  textBold: {
    fontWeight: '500',
    color: '#000',
  },
  buttonTouchable: {
    fontSize: 21,
    backgroundColor: '#ff0066',
    marginTop: 32,

    width: deviceWidth - 62,
    justifyContent: 'center',
    alignItems: 'center',
    height: 44
  },
  buttonTextStyle: {
    color: 'white',
    fontWeight: 'bold',
  }

});

 

 

참고)

 

react native qrcode 공식

 

https://blog.hackajob.co/how-to-build-a-qrcode-reader-using-reactnative/

 

예제 코드

https://enappd.com/blog/react-native-qr-code-scanning-using-react-native-camera/117/

 

예제 코드 git

https://github.com/enappd/RNQRCodeScanning

 

최신 참고글

https://morioh.com/p/7aae6b2e5819

 

 

 

 

 

 

반응형