invertase / react-native-firebase

πŸ”₯ A well-tested feature-rich modular Firebase implementation for React Native. Supports both iOS & Android platforms for all Firebase services.
https://rnfirebase.io
Other
11.63k stars 2.2k forks source link

πŸ”₯ Failed to Build dynamic link on android #3086

Closed vaibhavhrt closed 4 years ago

vaibhavhrt commented 4 years ago

Issue

Describe your issue here

While trying to create dynamic links on Android I am getting error, IOS is working fine. Handling incoming links works fine in both ios and Android. Code to create dynamic link:

export const createDynamicLink = async (companyId, userId) => {
  const link = await dynamicLinks().buildLink({
    link: `https://www.example.com/v2/profile/${companyId}/`,
    domainUriPrefix: 'https://example.page.link',
    analytics: {
      source: 'In-App',
      medium: 'profieshare',
      campaign: 'Traffic_profileshare',
      content: JSON.stringify(userId),
      // error occurs regardless of weather I add android section or not
      android: {
        packageName: 'connect.network.tranzact',
      },
    },
  });
  return link;
};

The error from Android Studio logcat is:

    com.facebook.react.bridge.NoSuchKeyException: packageName
        at com.facebook.react.bridge.ReadableNativeMap.getNullableValue(ReadableNativeMap.java:122)
        at com.facebook.react.bridge.ReadableNativeMap.getNullableValue(ReadableNativeMap.java:126)
        at com.facebook.react.bridge.ReadableNativeMap.getString(ReadableNativeMap.java:161)
        at io.invertase.firebase.dynamiclinks.ReactNativeFirebaseDynamicLinksModule.buildAndroidParameters(ReactNativeFirebaseDynamicLinksModule.java:230)
        at io.invertase.firebase.dynamiclinks.ReactNativeFirebaseDynamicLinksModule.createDynamicLinkBuilder(ReactNativeFirebaseDynamicLinksModule.java:180)
        at io.invertase.firebase.dynamiclinks.ReactNativeFirebaseDynamicLinksModule.lambda$buildLink$0$ReactNativeFirebaseDynamicLinksModule(ReactNativeFirebaseDynamicLinksModule.java:61)
        at io.invertase.firebase.dynamiclinks.-$$Lambda$ReactNativeFirebaseDynamicLinksModule$RYTUu1dki_xdOp5-xzN6ncDcGkM.call(Unknown Source:4)
        at com.google.android.gms.tasks.zzv.run(Unknown Source:2)
        at java.util.concurrent.ThreadPoolExecutor.processTask(ThreadPoolExecutor.java:1187)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1152)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
        at java.lang.Thread.run(Thread.java:784)

Project Files

Javascript

Click To Expand

#### `package.json`: ```json { "name": "app", "version": "1.2.1", "private": true, "scripts": { "android": "react-native run-android", "ios": "react-native run-ios", "start": "react-native start", "test": "jest", "lint": "eslint '**/*.{js,jsx}'", "prettier": "prettier '**/*.{js,jsx}' -c", "prettier:fix": "prettier '**/*.{js,jsx}' --write", "android:bundleRelease": "cd android && ./gradlew bundleRelease", "android:assembleRelease": "cd android && ./gradlew assembleRelease" }, "dependencies": { "@react-native-community/async-storage": "^1.6.3", "@react-native-community/google-signin": "^3.0.3", "@react-native-community/netinfo": "^5.0.0", "@react-native-firebase/analytics": "^6.2.0", "@react-native-firebase/app": "^6.2.0", "@react-native-firebase/crashlytics": "^6.2.0", "@react-native-firebase/dynamic-links": "^6.2.0", "@react-native-firebase/messaging": "^6.2.0", "formik": "^2.0.6", "jwt-decode": "^2.2.0", "react": "16.9.0", "react-native": "0.61.5", "react-native-config": "^0.12.0", "react-native-elements": "^1.2.7", "react-native-gesture-handler": "^1.5.2", "react-native-image-crop-picker": "^0.26.2", "react-native-image-picker": "^1.1.0", "react-native-material-dropdown": "^0.11.1", "react-native-paper": "^3.4.0", "react-native-reanimated": "^1.4.0", "react-native-screens": "^1.0.0-alpha.23", "react-native-svg": "^9.13.6", "react-native-vector-icons": "^6.6.0", "react-native-walkthrough-tooltip": "^1.1.6", "react-native-webview": "^8.0.2", "react-navigation": "^4.0.10", "react-navigation-stack": "^1.10.3", "react-navigation-tabs": "^2.6.0", "react-redux": "^7.1.3", "redux": "^4.0.4", "redux-mock-store": "^1.5.3", "redux-thunk": "^2.3.0", "yup": "^0.27.0" }, "devDependencies": { "@babel/core": "^7.6.2", "@babel/runtime": "^7.6.2", "@react-native-community/eslint-config": "^0.0.5", "babel-jest": "^24.9.0", "eslint": "^6.5.1", "eslint-plugin-prettier": "^3.1.1", "jest": "^24.9.0", "metro-react-native-babel-preset": "^0.56.0", "prettier": "^1.19.1", "react-test-renderer": "16.9.0", "redux-devtools-extension": "^2.13.8", "redux-logger": "^3.0.6", "typescript": "^3.7.3" } } ``` #### `firebase.json` for react-native-firebase v6: ```json # N/A ``` ### iOS

Click To Expand

#### `ios/Podfile`: - [ ] I'm not using Pods - [x] I'm using Pods and my Podfile looks like: ```ruby # Uncomment the next line to define a global platform for your project platform :ios, '9.0' require_relative '../node_modules/@react-native-community/cli-platform-ios/native_modules' target 'TranzactNetwork' do # Pods for TranzactNetwork pod 'FBLazyVector', :path => "../node_modules/react-native/Libraries/FBLazyVector" pod 'FBReactNativeSpec', :path => "../node_modules/react-native/Libraries/FBReactNativeSpec" pod 'RCTRequired', :path => "../node_modules/react-native/Libraries/RCTRequired" pod 'RCTTypeSafety', :path => "../node_modules/react-native/Libraries/TypeSafety" pod 'React', :path => '../node_modules/react-native/' pod 'React-Core', :path => '../node_modules/react-native/' pod 'React-CoreModules', :path => '../node_modules/react-native/React/CoreModules' pod 'React-Core/DevSupport', :path => '../node_modules/react-native/' pod 'React-RCTActionSheet', :path => '../node_modules/react-native/Libraries/ActionSheetIOS' pod 'React-RCTAnimation', :path => '../node_modules/react-native/Libraries/NativeAnimation' pod 'React-RCTBlob', :path => '../node_modules/react-native/Libraries/Blob' pod 'React-RCTImage', :path => '../node_modules/react-native/Libraries/Image' pod 'React-RCTLinking', :path => '../node_modules/react-native/Libraries/LinkingIOS' pod 'React-RCTNetwork', :path => '../node_modules/react-native/Libraries/Network' pod 'React-RCTSettings', :path => '../node_modules/react-native/Libraries/Settings' pod 'React-RCTText', :path => '../node_modules/react-native/Libraries/Text' pod 'React-RCTVibration', :path => '../node_modules/react-native/Libraries/Vibration' pod 'React-Core/RCTWebSocket', :path => '../node_modules/react-native/' pod 'React-cxxreact', :path => '../node_modules/react-native/ReactCommon/cxxreact' pod 'React-jsi', :path => '../node_modules/react-native/ReactCommon/jsi' pod 'React-jsiexecutor', :path => '../node_modules/react-native/ReactCommon/jsiexecutor' pod 'React-jsinspector', :path => '../node_modules/react-native/ReactCommon/jsinspector' pod 'ReactCommon/jscallinvoker', :path => "../node_modules/react-native/ReactCommon" pod 'ReactCommon/turbomodule/core', :path => "../node_modules/react-native/ReactCommon" pod 'Yoga', :path => '../node_modules/react-native/ReactCommon/yoga' pod 'DoubleConversion', :podspec => '../node_modules/react-native/third-party-podspecs/DoubleConversion.podspec' pod 'glog', :podspec => '../node_modules/react-native/third-party-podspecs/glog.podspec' pod 'Folly', :podspec => '../node_modules/react-native/third-party-podspecs/Folly.podspec' pod 'GoogleSignIn', '~> 5.0.2' target 'TranzactNetworkTests' do inherit! :search_paths # Pods for testing end use_native_modules! end target 'TranzactNetwork-tvOS' do # Pods for TranzactNetwork-tvOS target 'TranzactNetwork-tvOSTests' do inherit! :search_paths # Pods for testing end end ``` #### `AppDelegate.m`: ```objc /** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ @import Firebase; #import "AppDelegate.h" #import #import #import #import @implementation AppDelegate - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { if ([FIRApp defaultApp] == nil) { [FIRApp configure]; } RCTBridge *bridge = [[RCTBridge alloc] initWithDelegate:self launchOptions:launchOptions]; RCTRootView *rootView = [[RCTRootView alloc] initWithBridge:bridge moduleName:@"TranzactNetwork" initialProperties:nil]; rootView.backgroundColor = [[UIColor alloc] initWithRed:1.0f green:1.0f blue:1.0f alpha:1]; self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds]; UIViewController *rootViewController = [UIViewController new]; rootViewController.view = rootView; self.window.rootViewController = rootViewController; [self.window makeKeyAndVisible]; return YES; } - (NSURL *)sourceURLForBridge:(RCTBridge *)bridge { #if DEBUG return [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index" fallbackResource:nil]; #else return [[NSBundle mainBundle] URLForResource:@"main" withExtension:@"jsbundle"]; #endif } - (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary *)options { return [RCTLinkingManager application:app openURL:url options:options]; } @end ```

--- ### Android
Click To Expand

#### Have you converted to AndroidX? - [x] my application is an AndroidX application? - [ ] I am using `android/gradle.settings` `jetifier=true` for Android compatibility? - [ ] I am using the NPM package `jetifier` for react-native compatibility? #### `android/build.gradle`: ```groovy // Top-level build file where you can add configuration options common to all sub-projects/modules. buildscript { ext { buildToolsVersion = "28.0.3" minSdkVersion = 16 compileSdkVersion = 28 targetSdkVersion = 28 // supportLibVersion = "27.1.1" // # Remove 'supportLibVersion' property and put specific versions for AndroidX libraries androidXCore = "1.0.2" googlePlayServicesAuthVersion = "16.0.1" // <--- use this version or newer } repositories { google() jcenter() maven { url 'https://maven.fabric.io/public' } } dependencies { classpath('com.android.tools.build:gradle:3.5.3') classpath("com.google.gms:google-services:4.3.3") classpath("io.fabric.tools:gradle:1.31.2") // NOTE: Do not place your application dependencies here; they belong // in the individual module build.gradle files } } allprojects { repositories { mavenLocal() maven { // All of React Native (JS, Obj-C sources, Android binaries) is installed from npm url("$rootDir/../node_modules/react-native/android") } maven { // Android JSC is installed from npm url("$rootDir/../node_modules/jsc-android/dist") } google() jcenter() maven { url 'https://jitpack.io' } } } ``` #### `android/app/build.gradle`: ```groovy apply plugin: "com.android.application" apply plugin: 'io.fabric' apply from: project(':react-native-config').projectDir.getPath() + "/dotenv.gradle" import com.android.build.OutputFile /** * 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.android.bundle", * * // the entry file for bundle generation * entryFile: "index.android.js", * * // https://facebook.github.io/react-native/docs/performance#enable-the-ram-format * bundleCommand: "ram-bundle", * * // 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, * * // whether to disable dev mode in custom build variants (by default only disabled in release) * // for example: to disable dev mode in the staging build type (if configured) * devDisabledInStaging: true, * // The configuration property can be in the following formats * // 'devDisabledIn${productFlavor}${buildType}' * // 'devDisabledIn${buildType}' * * // 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: [] * ] */ crashlytics { enableNdk true } project.ext.react = [ entryFile: "index.js", enableHermes: false, // clean and rebuild if changing ] apply from: "../../node_modules/react-native/react.gradle" /** * Set this to true to create two separate APKs instead of one: * - An APK that only works on ARM devices * - An APK that only works on x86 devices * The advantage is the size of the APK is reduced by about 4MB. * Upload all the APKs to the Play Store and people will download * the correct one based on the CPU architecture of their device. */ def enableSeparateBuildPerCPUArchitecture = false /** * Run Proguard to shrink the Java bytecode in release builds. */ def enableProguardInReleaseBuilds = true /** * The preferred build flavor of JavaScriptCore. * * For example, to use the international variant, you can use: * `def jscFlavor = 'org.webkit:android-jsc-intl:+'` * * The international variant includes ICU i18n library and necessary data * allowing to use e.g. `Date.toLocaleString` and `String.localeCompare` that * give correct results when using with locales other than en-US. Note that * this variant is about 6MiB larger per architecture than default. */ def jscFlavor = 'org.webkit:android-jsc:+' /** * Whether to enable the Hermes VM. * * This should be set on project.ext.react and mirrored here. If it is not set * on project.ext.react, JavaScript will not be compiled to Hermes Bytecode * and the benefits of using Hermes will therefore be sharply reduced. */ def enableHermes = project.ext.react.get("enableHermes", false); android { compileSdkVersion rootProject.ext.compileSdkVersion compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 } defaultConfig { applicationId "connect.network.tranzact" minSdkVersion rootProject.ext.minSdkVersion targetSdkVersion rootProject.ext.targetSdkVersion manifestPlaceholders = [icon:project.env.get("ICON"), roundIcon:project.env.get("ROUND_ICON")] versionCode 5 versionName "1.2.1" } splits { abi { reset() enable enableSeparateBuildPerCPUArchitecture universalApk true // If true, also generate a universal APK include "armeabi-v7a", "x86", "arm64-v8a", "x86_64" } } signingConfigs { debug { storeFile file('debug.keystore') storePassword 'android' keyAlias 'androiddebugkey' keyPassword 'android' } release { if (project.hasProperty('MYAPP_UPLOAD_STORE_FILE')) { storeFile file(MYAPP_UPLOAD_STORE_FILE) storePassword MYAPP_UPLOAD_STORE_PASSWORD keyAlias MYAPP_UPLOAD_KEY_ALIAS keyPassword MYAPP_UPLOAD_KEY_PASSWORD } } } buildTypes { debug { signingConfig signingConfigs.debug } release { // Caution! In production, you need to generate your own keystore file. // see https://facebook.github.io/react-native/docs/signed-apk-android. signingConfig signingConfigs.release minifyEnabled enableProguardInReleaseBuilds proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro" } } // applicationVariants are e.g. debug, release applicationVariants.all { variant -> variant.outputs.each { output -> // For each separate APK per architecture, set a unique version code as described here: // https://developer.android.com/studio/build/configure-apk-splits.html def versionCodes = ["armeabi-v7a": 1, "x86": 2, "arm64-v8a": 3, "x86_64": 4] def abi = output.getFilter(OutputFile.ABI) if (abi != null) { // null for the universal-debug, universal-release variants output.versionCodeOverride = versionCodes.get(abi) * 1048576 + defaultConfig.versionCode } } } } dependencies { implementation fileTree(dir: "libs", include: ["*.jar"]) implementation "com.facebook.react:react-native:+" // From node_modules if (enableHermes) { def hermesPath = "../../node_modules/hermes-engine/android/"; debugImplementation files(hermesPath + "hermes-debug.aar") releaseImplementation files(hermesPath + "hermes-release.aar") } else { implementation jscFlavor } implementation 'androidx.appcompat:appcompat:1.1.0-rc01' implementation 'androidx.swiperefreshlayout:swiperefreshlayout:1.1.0-alpha02' implementation 'com.google.firebase:firebase-analytics:17.2.1' implementation 'com.crashlytics.sdk.android:crashlytics:2.10.1' // implementation 'com.google.firebase:firebase-dynamic-links:19.0.0' } // Run this once to be able to run the application with BUCK // puts all compile dependencies into folder libs for BUCK to use task copyDownloadableDepsToLibs(type: Copy) { from configurations.compile into 'libs' } apply from: file("../../node_modules/@react-native-community/cli-platform-android/native_modules.gradle"); applyNativeModulesAppBuildGradle(project) // React Native Vector Icons project.ext.vectoricons = [ iconFontNames: ['MaterialIcons.ttf', 'MaterialCommunityIcons.ttf'] ] apply from: "../../node_modules/react-native-vector-icons/fonts.gradle" apply plugin: 'com.google.gms.google-services' ``` #### `android/settings.gradle`: ```groovy rootProject.name = 'TranzactNetwork' apply from: file("../node_modules/@react-native-community/cli-platform-android/native_modules.gradle"); applyNativeModulesSettingsGradle(settings) include ':app' ``` #### `MainApplication.java`: ```java package connect.network.tranzact; import android.app.Application; import android.content.Context; import com.facebook.react.PackageList; import com.facebook.react.ReactApplication; import com.facebook.react.ReactNativeHost; import com.facebook.react.ReactPackage; import com.facebook.soloader.SoLoader; import java.lang.reflect.InvocationTargetException; import java.util.List; public class MainApplication extends Application implements ReactApplication { private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) { @Override public boolean getUseDeveloperSupport() { return BuildConfig.DEBUG; } @Override protected List getPackages() { @SuppressWarnings("UnnecessaryLocalVariable") List packages = new PackageList(this).getPackages(); // Packages that cannot be autolinked yet can be added manually here, for example: // packages.add(new MyReactNativePackage()); return packages; } @Override protected String getJSMainModuleName() { return "index"; } }; @Override public ReactNativeHost getReactNativeHost() { return mReactNativeHost; } @Override public void onCreate() { super.onCreate(); SoLoader.init(this, /* native exopackage */ false); initializeFlipper(this); // Remove this line if you don't want Flipper enabled } /** * Loads Flipper in React Native templates. * * @param context */ private static void initializeFlipper(Context context) { if (BuildConfig.DEBUG) { try { /* We use reflection here to pick up the class that initializes Flipper, since Flipper library is not available in release mode */ Class aClass = Class.forName("com.facebook.flipper.ReactNativeFlipper"); aClass.getMethod("initializeFlipper", Context.class).invoke(null, context); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } } } } ``` #### `AndroidManifest.xml`: ```xml ```

--- ## Environment
Click To Expand

**`react-native info` output:** ``` OUTPUT GOES HERE ``` - **Platform that you're experiencing the issue on**: - [ ] iOS - [x] Android - [ ] **iOS** but have not tested behavior on Android - [ ] **Android** but have not tested behavior on iOS - [ ] Both - **`react-native-firebase` version you're using that has this issue:** - `6.2.0` - **`Firebase` module(s) you're using that has the issue:** - `dynamicLinks().buildLink, dynamicLinks().buildShortLink` - **Are you using `TypeScript`?** - `N`

--- Think `react-native-firebase` is great? Please consider supporting all of the project maintainers and contributors by donating via our [Open Collective](https://opencollective.com/react-native-firebase/donate) where all contributors can submit expenses. [[Learn More]](https://invertase.io/oss/react-native-firebase/contributing/donations-expenses) - πŸ‘‰ Check out [`React Native Firebase`](https://twitter.com/rnfirebase) and [`Invertase`](https://twitter.com/invertaseio) on Twitter for updates on the library.
vaibhavhrt commented 4 years ago

never mind, solved after putting android section at correct place. But docs says android section is not required.

Salakar commented 4 years ago

@vaibhavhrt Is the code code example you provided one that was causing the above error? Looking at the code and there is checks in place to prevent this from even happening:

https://github.com/invertase/react-native-firebase/blob/master/packages/dynamic-links/android/src/main/java/io/invertase/firebase/dynamiclinks/ReactNativeFirebaseDynamicLinksModule.java#L179-L181

https://github.com/invertase/react-native-firebase/blob/master/packages/dynamic-links/lib/builder.js#L78-L80

https://github.com/invertase/react-native-firebase/blob/master/packages/dynamic-links/lib/builders/android.js#L51-L53

vaibhavhrt commented 4 years ago

Building links on android fails if I don't provide android section with packageName. I thought it will pick packageName automatically from google-service.json but it isn't. I don't have firebase.json, just google-service.json. on iOS it works without any issue.

Works πŸ‘‡

{
      link: 'https://example.com',
      domainUriPrefix: 'https://tranzactnetwork.page.link',
      android: {
        packageName: 'xxx.xxx.xxx',
      },
}

Doesn't Works πŸ‘‡

{
      link: 'https://example.com',
      domainUriPrefix: 'https://tranzactnetwork.page.link',
      //android: {
      //  packageName: 'xxx.xxx.xxx',
      //},
}
Salakar commented 4 years ago

Thanks for confirming, we'll get this looked at.

russellwheatley commented 4 years ago

@vaibhavhrt This bug has been fixed as part of this PR #3171, and will be part of the next release. Thanks for raising this issue.

vaibhavhrt commented 4 years ago

@russellwheatley thanks for the fix.