Einleitung
Seit seiner Veröffentlichung im Jahr 2013 gewinnt React in der Welt der Softwareentwicklung immer mehr an Bedeutung. Reactive Design Pattern ist ein bekannter Begriff geworden, obwohl dessen Entstehung leicht umstritten war.
In 2015, Facebook’s development team delved into the world of mobile development and created its framework called React Native. As of the past few years, React Native has proven itself to be a formidable force in Cross-Platform Mobile Development. Let's build a Scanbot Barcode Scanner App with React Native.
Erste Schritte mit React
Tools
First off, React Native does not work magically. In layman's terms, it's just a blanket on top of a native iOS and Android app that offers a unified API for rendering views. Therefore, we require the same basic mobile development tools as if we were doing it in Java or Objective-C:
- Xcode & CocoaPods
- Android Studio
Then, it's wise to have Java and path set in your way. If you're on a clean installation of Android Studio and haven't made any previous Java- or Gradle-related installs, it shouldn't be necessary. This will let the React CLI know which Java to use if you've downloaded several versions of it. OpenJDK 8, welches Sie einfach herunterladen und installieren können, ist die vorteilhafteste Option für die Android-Entwicklung (11 sollte in Ordnung sein, 14 ist schwierig mit älteren Versionen von Gradle).
Auf Mac oder Linux wechseln Sie nun zu /Users/$USER/ und öffnen .bash_profile, .zshrc oder .bashrc mit Ihrem bevorzugten Texteditor, um die folgenden Zeilen hinzuzufügen:
export JAVA_HOME=/Library/Java/JavaVirtualMachines/adoptopenjdk-8.jdk/Contents/Home
export ANDROID_HOME=/Users/$USER/Library/Android/sdk
export PATH=${PATH}:$ANDROID_HOME/tools:$ANDROID_HOME/platform-tools
Danach geben Sie source <filename> to reload the file. That's it!
Beachten Sie, dass platform-tools ebenfalls dem Pfad hinzugefügt wurde. Das ist nicht erforderlich, aber sehr praktisch, um alle möglichen Dinge zu debuggen, vor allem zeigt der Befehl adb devices an, ob Sie ein debuggbares Gerät zur Verfügung haben oder nicht.
Und schließlich die Programme, die für die ordnungsgemäße Funktion der React Native-Layer erforderlich sind:
Installieren Sie alles bevorzugterweise über brew. Das Einrichten ist relativ simpel. Installieren Sie zuerst brew:
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install.sh)"
Then, make sure it's up to date and install node:
brew update
brew install node
You're now just about ready to start coding. One last hint from the official React Native environment setup guide:
React Native hat eine integrierte Befehlszeilen-Schnittstelle. Anstatt eine bestimmte Version der CLI global zu installieren und zu verwalten, empfehlen wir Ihnen, zur Laufzeit über npx, welches im Lieferumfang von Node.js enthalten ist, auf die aktuelle Version zuzugreifen. Mit npx react-native <command> wird die aktuelle, stabile Version der CLI heruntergeladen und zum Zeitpunkt der Ausführung des Befehls durchgeführt.
Hello World!
The hard part was setting up the environment. From now on, the integration is going to be smooth sailing. We'll be using typescript for this example, as it is the recommended approach for writing JavaScript these days. Run the following:
npx react-native init ScanbotApp --template react-native-template-typescript
That should take a couple of minutes, but it's also an awesome one-liner that does everything for you: From creating and configuring the native projects to npm install. After this has been done, simply:
cd ScanbotApp
react-native run-android
Sie sollten nun dieses Bild sehen:
Scanbot SDK
Now we finally get to the good stuff – Scanbot! If you're reading this, you're probably aware of what npm is; nevertheless, in short, your "Hello World" app has a file called package.json that defines all the dependencies you have. As you can see, React Native itself already defines a lot of them, everything from linters to typescript to jsx syntax.
Let's add another one (to dependencies, not devDependencies, as we need the ScanbotSDK during runtime as well, not just for development purposes) and then install it via npm install:
"react-native-scanbot-sdk": "4.1.0"
iOS
Da das Scanbot SDK für React Native ein Wrapper der nativen Version ist, besteht ein zusätzlicher Schritt darin, auch das native SDK herunterzuladen. Ab der React Native Version 0.62 werden die nativen Abhängigkeiten automatisch aufgelöst. Sie müssen nichts zum Podfile (Natives iOS Äquivalent von package.json) hinzufügen, aber Sie müssen trotzdem in den iOS-Ordner gehen und die nativen Abhängigkeiten installieren:
cd ios
pod install
That was almost too easy, wasn't it? Well, this isn't over yet.
Android
As with most things in mobile development, you expect the android equivalent of something to be a bit more difficult to configure. This isn't necessarily a bad thing, quite the opposite, having more options to configure is mostly a good a thing. It can get somewhat frustrating, though.
Für die Konfiguration von Anforderungen auf Gradle-Ebene empfehlen wir die Verwendung von Android Studio, da es eine bessere Syntaxhervorhebung und eine visuelle Schnittstelle bietet. Sie können natürlich auch einen beliebigen Texteditor verwenden - sogar Notepad ist geeignet.
First, you should enable MultiDex. That's done via adding multiDexEnabled true to your android/app/build.gradle as such:
defaultConfig {
applicationId "com.scanbotapp"
minSdkVersion rootProject.ext.minSdkVersion
targetSdkVersion rootProject.ext.targetSdkVersion
versionCode 1
versionName "1.0"
multiDexEnabled true
}
Enabling MultiDex is just a fancy way of saying "Yes, I know this app has a heavy-weight ML-based document scanning SDK and I don't care".
Innerhalb derselben Datei sollten Sie zudem spezifizieren, dass die erste Instanz von libc++_shared.so wie folgt auf demselben Level der defaultConfig ausgewählt wird:
packagingOptions {
pickFirst '**/libc++_shared.so'
}
Dies muss angegeben werden, da viele Abhängigkeiten von Drittanbietern über native Binaries verfügen, die die gemeinsam genutzte C++-Bibliothek verwenden (im Kontext von Gradle ist React Native selbst eine dritte Abhängigkeit die diese verwendet, ebenso wie das Scanbot SDK).
Another thing you should add is android:largeHeap="true" and that under your application tag of android/app/src/main/AndroidManifest.xml file, as such:
<application
android:largeHeap="true"
android:name=".MainApplication"
...
Als Nächstes müssen Sie den Scanbot SDK Pfad zu Ihrem application-Level Gradle hinzufügen (android/build.gradle). So weiß Gradle genau, wo unser SDK zu finden ist:
allprojects {
repositories {
...
// Scanbot SDK Maven repositories:
maven { url 'https://nexus.scanbot.io/nexus/content/repositories/releases/' }
maven { url 'https://nexus.scanbot.io/nexus/content/repositories/snapshots/' }
}
}
Genau dort, in Ihrem application-level Gradle, sollten Sie auch die minSdkVersion auf 21 erhöhen, da dies eine Anforderung für die neueste Version des Scanbot SDK darstellt (und das ist, sofern nicht ausdrücklich anders gewünscht, im Allgemeinen eine gute Idee - die Unterstützung der Abwärtskompatibilität unter Android 5.0 ist ein Albtraum).
Und zuletzt legen Sie fest, wo react-native-scanbot-sdk sich in Ihrem Repository befindet. Dies wird erreicht, indem man die folgenden Zeilen zur android/settings.gradle hinzufügt:
include ':react-native-scanbot-sdk'
project(':react-native-scanbot-sdk').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-scanbot-sdk/android/app')
React-Native
Falls Sie dieselbe App-Vorlage nutzen, sollten Sie auch in der Lage sein, das Folgende durchzuführen. Der Einfachheit halber fügen Sie der TextView einen Click-Handler hinzu, zum Beispiel wird die folgende Zeile:
<Text style={styles.sectionTitle} >Step One</Text>
zu:
<Text
style={styles.sectionTitle}
onPress={() => {
console.log('Hello click-handler!');
}}>
Step One
</Text>
Then, let's just create a global variable to decide what our click-handler should do:
let initialized = false;
Now that the basics are out of the way, it's time to start working with the SDK.
Bevor Sie beginnen, sollten Sie die Importe definieren. Für dieses Beispiel benötigen Sie nur drei Dinge. Das SDK selbst und dann zwei Options- und Konfigurationsklassen:
import ScanbotSDK, {
BarcodeScannerConfiguration,
InitializationOptions,
} from 'react-native-scanbot-sdk/src';
Der erste richtige Schritt ist die Initialisierung. Dies geht wie folgt:
const options: InitializationOptions = {
licenseKey: '',
};
await ScanbotSDK.initializeSDK(options);
Um den QR- und Barcode-Scanner zu starten, sieht der Codeschnipsel wie folgt aus:
const configuration: BarcodeScannerConfiguration = {};
const result = await ScanbotSDK.UI.startBarcodeScanner(configuration);
Nur zur Übersicht, Ihr vollständiges onPress sollte so aussehen:
onPress={async () => {
if (!initialized) {
const options: InitializationOptions = {
licenseKey: '',
};
await ScanbotSDK.initializeSDK(options);
initialized = true;
Alert.alert("SDK initialized", "Press me again to start Barcode Scanner");
} else {
const configuration: BarcodeScannerConfiguration = {};
const result = await ScanbotSDK.UI.startBarcodeScanner(configuration);
if (result?.barcodes?.length > 0) {
Alert.alert("Barcode detected", result.barcodes[0].text);
}
}
}}>
Now that we've got everything sorted out, go ahead and scan the following QR code:
Zusammenfassung & Referenzen
Während jede plattformübergreifende Lösung Ihre Probleme hat, wie z.B. interne Inkonsistenzen, gestaltet die Einfachheit und Eleganz von React die Softwareentwicklung sehr reibungslos und unterhaltsam.
Wenn Sie mehr über die Möglichkeiten von React Native und das Scanbot SDK wissen möchten, schauen Sie sich die folgenden Links an:
- Entdecken Sie die Funktionen des Scanbot SDK in unserer Demo App
- Werfen Sie einen Blick in unsere umfangreiche Dokumentation
As always, feel free to contact one of our experts for further information about the Scanbot SDK and its integration. We'd love to find the perfect solution for you. Let's talk.