テンプレートプロジェクトの検索
学習の目的
この単元を完了すると、次のことができるようになります。
- Mobile SDK React Native アプリケーションのプロジェクト構造を理解する。
- デバッグまたは本番用プロジェクトを設定する。
- GitHub で Mobile SDK React Native サンプルアプリケーションを見つけてソースライブラリを開く。
React Native の Mobile SDK テンプレート
forcereact を使用してアプリケーションを作成すると、指定した引数でテンプレートがカスタマイズされます。このカスタマイズされたテンプレートが、新しい Mobile SDK アプリケーションのプロジェクトです。React Native の場合、テンプレートは、ネイティブオペレーティングシステムへの直接アクセスを提供するネイティブコンテナアプリケーションを定義します。このコンテナは、JavaScript コードと、Android または iOS ランタイムのブリッジを提供します。場合によっては、開発ニーズでこの基盤コンテナへの調整が求められることがあります。そのアプリケーションの内容を詳しく見てみましょう。
iOS ネイティブコンテナ
テンプレートプロジェクトの iOS ネイティブ部分は、ネイティブ iOS プロジェクトのものとほぼ同じです。2 つのクラスが次に対応します。
- 起動用 Mobile SDK の設定
- ルートビューのインスタンス化と表示
- ログインおよび認証の開始と処理
Xcode で <output_directory>/ios/FirstReact.xcworkspace を開きます。ワークスペースをざっと見ると、ネイティブ iOS プロジェクトを見ているように感じます。たとえば、AppDelegate クラスには、ネイティブ iOS アプリケーションの多くの定型コードが含まれます。React 専用コードは、AppDelegate の setupRootViewController メソッドに存在します。
このメソッドは、React Native クラスである RCTRootView のインスタンスを作成し、そのインスタンスをアプリケーションのルートビューに割り当てます。RCTRootView は、ネイティブ UI コンポーネントと、アプリケーションの React Native コンポーネントのブリッジとして機能します。JavaScript コードを含むバンドルの場所 (jsCodeLocation) でこのクラスを初期化することに注目します。
- (void)setupRootViewController
{
NSURL *jsCodeLocation;
jsCodeLocation = [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index"
fallbackResource:nil];
RCTRootView *rootView = [[RCTRootView alloc] initWithBundleURL:jsCodeLocation
moduleName:@"SecondReact"
initialProperties:nil
launchOptions:self.launchOptions];
rootView.backgroundColor = [[UIColor alloc] initWithRed:1.0f
green:1.0f
blue:1.0f
alpha:1];
UIViewController *rootViewController = [UIViewController new];
rootViewController.view = rootView;
self.window.rootViewController = rootViewController;
}
Android ネイティブコンテナ
Android Studio で FirstReact/android プロジェクトを開き、プロジェクトビューに移動して、FirstReact/app/app/src/main/java/com.mytrail.react の下を表示します。2 つのネイティブ Java クラス、MainActivity と MainApplication を確認できます。これらのクラスは、いわば、ネイティブのみの Mobile SDK に相当します。
MainApplication と MainActivity クラスは、Android ネイティブプロジェクトの場合と同じように次を行います。
- 起動用 Mobile SDK の設定
- 起動アクティビティのインスタンス化と表示
- ログインおよび認証の開始と処理
これらのクラスの、ネイティブと React Native テンプレートの一番の違いは基本クラスです。React Native アプリケーションでは、MainApplication は通常、Application を拡張しますが、ReactApplication の実装も行います。MainActivity は SalesforceReactActivity を拡張し、さらにそれが ReactActivity を拡張します。ReactApplication と ReactActivity は、Facebook React Native ライブラリのものです。実装を詳しく確認すると、多くのコードパスが最終的に React Native オブジェクトにつながっていることがわかります。これらのオブジェクトには、SalesforceReactSDKManager のように、多くの Mobile SDK クラスの React 重視の特化が含まれています。
たとえば、MainApplication コードは ReactNativeHost オブジェクトを作成し、それを使用して、Mobile SDK React Native パッケージを React Native フレームワークに渡します。
private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) {
@Override
public boolean getUseDeveloperSupport() {
return BuildConfig.DEBUG;
}
@Override
protected List<ReactPackage> getPackages() {
@SuppressWarnings("UnnecessaryLocalVariable")
List<ReactPackage> packages = new PackageList(this).getPackages();
// Packages that cannot be autolinked yet can be added manually here, for example:
// packages.add(new MyReactNativePackage());
packages.add(SalesforceReactSDKManager.getInstance().getReactPackage());
return packages;
}
@Override
protected String getJSMainModuleName() {
return "index";
}
};SalesforceReactSDKManager.getReactPackage() コードを詳しく確認すると、このコードが新しい ReactPackage オブジェクトを返すことを確認できます。このオブジェクトは、createNativeModules() 基本メソッドを上書きして、期待するとおりのパッケージのリストを返します。
@Override public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) {
List<NativeModule> modules = new ArrayList<>();
modules.add(new SalesforceOauthReactBridge(reactContext));
modules.add(new SalesforceNetReactBridge(reactContext));
modules.add(new SmartStoreReactBridge(reactContext));
modules.add(new MobileSyncReactBridge(reactContext));
return modules;
}React Native ランタイムはこのメソッドをコールして、それ以外は上書きにより、ネイティブ Mobile SDK コードとして JavaScript メソッドを実行する魔法を作り出します。
ビルドの設定
デバッグまたはリリースモードで実行するためのコードの設定場所をお探しですか? そのメカニズムは、Android と iOS で少し異なります。開発またはデバッグ時、Android Studio は、開発サーバーから直接 JS ファイルを読み込むことを想定します。リリースモードの場合、デバイスのバンドルから JS ファイルを読み込みます。プロジェクトの android/app/build.gradle ファイルのデフォルトのビルド設定を上書きできます。ファイルの先頭にある長いコメント内の説明に従います。次に例を示します。
/*** The react.gradle file registers a task for each build variant (e.g. bundleDebugJsAndAssets
* and bundleReleaseJsAndAssets).
* These basically call `react-native bundle` with the correct arguments during the Android build
* cycle. By default, bundleDebugJsAndAssets is skipped, as in debug/dev mode we prefer to load the
* bundle directly from the development server. Below you can see all the possible configurations
* and their defaults. If you decide to add a configuration block, make sure to add it before the
* `apply from: "../../node_modules/react-native/react.gradle"` line.
*
* project.ext.react = [
* // the name of the generated asset file containing your JS bundle
* bundleAssetName: "index.bundle",
*
* // the entry file for bundle generation
* entryFile: "index.js",
*
* // whether to bundle JS and assets in debug mode
* bundleInDebug: false,
*
* // whether to bundle JS and assets in release mode
* bundleInRelease: true,
*
* // whether to bundle JS and assets in another build variant (if configured).
* // See http://tools.android.com/tech-docs/new-build-system/user-guide#TOC-Build-Variants
* // The configuration property can be in the following formats
* // 'bundleIn${productFlavor}${buildType}'
* // 'bundleIn${buildType}'
* // bundleInFreeDebug: true,
* // bundleInPaidRelease: true,
* // bundleInBeta: true,
*
* // the root of your project, i.e. where "package.json" lives
* root: "../../",
*
* // where to put the JS bundle asset in debug mode
* jsBundleDirDebug: "$buildDir/intermediates/assets/debug",
*
* // where to put the JS bundle asset in release mode
* jsBundleDirRelease: "$buildDir/intermediates/assets/release",
*
* // where to put drawable resources / React Native assets, e.g. the ones you use via
* // require('./image.png')), in debug mode
* resourcesDirDebug: "$buildDir/intermediates/res/merged/debug",
*
* // where to put drawable resources / React Native assets, e.g. the ones you use via
* // require('./image.png')), in release mode* resourcesDirRelease: "$buildDir/intermediates/res/merged/release",
*
* // by default the gradle tasks are skipped if none of the JS files or assets change; this means
* // that we don't look at files in android/ or ios/ to determine whether the tasks are up to
* // date; if you have any other folders that you want to ignore for performance reasons (gradle
* // indexes the entire tree), add them here. Alternatively, if you have JS files in android/
* // for example, you might want to remove it from here.
* inputExcludes: ["android/**", "ios/**"],
*
* // override which node gets called and with what additional arguments
* nodeExecutableAndArgs: ["node"]
*
* // supply additional arguments to the packager
* extraPackagerArgs: []
* ]
*/
iOS では、デバッグモードとリリースモードの切り替えは自動的に処理されます。
React Native の Mobile SDK サンプルアプリケーション
さらに独自でさまざまなことを試す場合、GitHub の SalesforceMobileSDK-Templates リポジトリの MobileSyncExplorerReactNative サンプルアプリケーションを確認します。このサンプルでは、これまでに学習したすべての React Native 言語と、まだ学習していない次の Mobile SDK オフライン機能のデモを行えます。
- SmartStore –– デバイスに安全にデータを格納するオフラインキャッシュメカニズム。
- Mobile Sync –– デバイスの接続回復時に、オフラインのデータ変更をソース Salesforce レコードに簡単にマージできるオフライン同期メカニズム。
開発マシンで MobileSyncExplorerReactNative サンプルアプリケーションを作成するには、forcereact createwithtemplate コマンドを使用します。次に例を示します。
% forcereact createwithtemplate Enter the target platform(s) separated by commas (ios, android): ios,android Enter URI of repo containing template application or a Mobile SDK template name: MobileSyncExplorerReactNative Enter your application name: MyMobileSyncExplorer Enter your package name: com.mytrail.react Enter your organization name (Acme, Inc.): MyTrail Enter output directory for your app (leave empty for the current directory): MyMobileSyncExplorer
アプリケーションを実行するには、React Native 開発サーバーを起動します。
- macOS のターミナルウィンドウまたは Windows のコマンドプロンプトで、アプリケーションのルートディレクトリに変更します。今回の場合、MyMobileSyncExplorer/ です。
- 次のいずれかのコマンドを実行します。
- macOS の場合: yarn start または npm start
- Windows の場合: yarn run-script start-windows または npm run-script start-windows
コマンドラインが「To open developer menu press 'd’ (開発者メニューを開くには、「d」を押してください)」と報告すると、開発環境からアプリケーションを実行できます。
- iOS の場合:
- Xcode で MyMobileSyncExplorer/ios/MyMobileSyncExplorer.xcworkspace を開きます。
- [実行] をクリックします。
- Android の場合:
- Android Studio のようこそ画面、または [File (ファイル)] | [Open (開く)] メニュー項目で、MyMobileSyncExplorer/android/ に移動します。
- [OK] をクリックします。
- [実行] をクリックします。
詳細の確認
ネイティブライブラリプロジェクトで、Mobile SDK と React Native の間のブリッジがどのように定義されているかを調べるには、次を確認します。
- iOS: SalesforceMobileSDK-ReactNative リポジトリの ios/SalesforceReact プロジェクト。
- Android: SalesforceMobileSDK-Android リポジトリの libs/SalesforceReact プロジェクト。
- リソース
- GitHub repo: React Native template for Mobile SDK (GitHub リポジトリ: Mobile SDK の React Native テンプレート)
- GitHub repo: MobileSyncExplorerReactNative
- GitHub repo: Mobile SDK React Native components for iOS (Mobile SDK React Native for iOS コンポーネント)
- GitHub repo: Mobile SDK React Native components for Android (Mobile SDK React Native for Android コンポーネント)
- SmartStore を使用したオフラインデータの安全な保存
- Mobile Sync を使用した Salesforce オブジェクトへのアクセス