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.54k stars 2.19k forks source link

Failed to create Dynamic Link #2350

Closed Base29 closed 4 years ago

Base29 commented 5 years ago

🔥

Issue

I have upgraded to RN 0.59.10 and now i cannot create dynamic links

My JS Implementation

import React, { Component } from 'react';
import { Text, View, Image, TouchableOpacity, Share, Alert } from 'react-native';
import firebase from 'react-native-firebase';
import styles from './styles';

const friendsGroup = require('../../../assets/images/friends-group.png');
const shareIcon = require('../../../assets/icons/share-icon.png');

class Referral extends Component {
    state = {
        shareLink: ''
    };
    onShare = async () => {
        try {
            const result = await Share.share({
                message: 'Hey found this new great app for ordering ... You should try it as well.',
                url: this.state.shareLink
            });

            if (result.action === Share.sharedAction) {
                if (result.activityType) {
                    // shared with activity type of result.activityType
                } else {
                    // shared
                }
            } else if (result.action === Share.dismissedAction) {
                // dismissed
            }
        } catch (error) {
            Alert.alert('Opps', error.message);
        }
    };

    onPressTermsCondition = () => {
        this.props.navigation.navigate('TermsAndConditions');
    };

    generateShareLink = async () => {
        console.log('PRESSED');
        const identifier = 'com.example.myapp';
        const firebaseDynamicLinkPrefix = 'myapp.page.link';
        const deepLink = 'https://www.example.com/?referralCode=foo&referralType=bar';
        const shareLink = new firebase.links.DynamicLink(
            deepLink,
            firebaseDynamicLinkPrefix
        ).android
            .setPackageName(identifier)
            .ios.setBundleId(identifier);

        console.log('SHARE LINK', shareLink);

        firebase
            .links()
            .createDynamicLink(shareLink)
            .then(url => {
                // ...
                console.log('LINK', url);
            })
            .catch(e => console.log('ERROR', e));

        // firebase
        //     .links()
        //     .createShortDynamicLink(shareLink, 'UNGUESSABLE')
        //     .then(url => {
        //         // ...
        //         console.log('URL', url);
        //         this.setState({ shareLink: url }, () => {
        //             //this.onShare();
        //             console.log('LINK SAVED');
        //         });
        //     })
        //     .catch(e => console.log('ERROR', e));
    };

    render() {
        return (
            <View style={styles.container}>
                <View style={styles.header}>
                    <View style={styles.heading}>
                        <Text style={styles.headingText}>Refer a friend</Text>
                    </View>
                    <View style={styles.subHeading}>
                        <Text style={styles.subHeadingText}>Share the Eat&#39;n Love</Text>
                    </View>
                </View>
                <View style={styles.content}>
                    <View style={styles.imageContainer}>
                        <Image source={friendsGroup} style={styles.image} />
                    </View>
                    <View style={styles.descriptionContainer}>
                        <Text style={styles.descriptionText}>
                            Get upto 10% discount when someone signs up using your referral code and
                            place their first order over $10. Your friend also gets $7 off.
                        </Text>
                    </View>
                    <View style={styles.sharingContainer}>
                        <View style={styles.sharingDescriptionContainer}>
                            <Text style={styles.sharingDescriptionText}>Tap to share</Text>
                        </View>
                        <View style={styles.shareButtonContainer}>
                            <TouchableOpacity
                                style={styles.shareButton}
                                onPress={() => this.generateShareLink()}
                            >
                                <View style={styles.shareIconContainer}>
                                    <Image source={shareIcon} style={styles.shareIcon} />
                                </View>
                                <View style={styles.referralCodeContainer}>
                                    <Text style={styles.referralCodeText}>89sd8293</Text>
                                </View>
                                <View style={styles.emptyView} />
                            </TouchableOpacity>
                        </View>
                    </View>
                </View>
                <View style={styles.termsContainer}>
                    <Text style={styles.termsText} onPress={() => this.onPressTermsCondition()}>
                        Terms&nbsp;&#38;&nbsp;Conditions
                    </Text>
                </View>
            </View>
        );
    }
}

export default Referral;

Project Files

iOS

Click To Expand

#### `ios/Podfile`: - [ ] I'm not using Pods - [x] I'm using Pods and my Podfile looks like: ```ruby pod 'Firebase/Core', '~> 6.3.0' pod 'Firebase/Messaging', '~> 6.3.0' pod 'Firebase/RemoteConfig', '~> 6.3.0' pod 'Firebase/Database', '~> 6.3.0' pod 'Firebase/DynamicLinks', '~> 6.3.0' ``` #### `AppDelegate.m`: ```objc #import "AppDelegate.h" #import #import #import "RNFirebaseMessaging.h" #import "RNFirebaseNotifications.h" #import #import #import "RNFirebaseLinks.h" #import #import #import "RNSplashScreen.h" // react native splash screen link @implementation AppDelegate - (void)applicationDidBecomeActive:(UIApplication *)application { [FBSDKAppEvents activateApp]; } - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { [FIROptions defaultOptions].deepLinkURLScheme = @"com.example.myapp"; [FIRApp configure]; [RNFirebaseNotifications configure]; [[FBSDKApplicationDelegate sharedInstance] application:application didFinishLaunchingWithOptions:launchOptions]; RCTBridge *bridge = [[RCTBridge alloc] initWithDelegate:self launchOptions:launchOptions]; RCTRootView *rootView = [[RCTRootView alloc] initWithBridge:bridge moduleName:@"MyApp" 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]; [RNSplashScreen show]; // react native splash screen link return YES; } - (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification { [[RNFirebaseNotifications instance] didReceiveLocalNotification:notification]; } - (void)application:(UIApplication *)application didReceiveRemoteNotification:(nonnull NSDictionary *)userInfo fetchCompletionHandler:(nonnull void (^)(UIBackgroundFetchResult))completionHandler{ [[RNFirebaseNotifications instance] didReceiveRemoteNotification:userInfo fetchCompletionHandler:completionHandler]; } - (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings { [[RNFirebaseMessaging instance] didRegisterUserNotificationSettings:notificationSettings]; } - (BOOL)application:(UIApplication *)application openURL:(NSURL *)url options:(NSDictionary *)options { return [[FBSDKApplicationDelegate sharedInstance] application:application openURL:url sourceApplication:options[UIApplicationOpenURLOptionsSourceApplicationKey] annotation:options[UIApplicationOpenURLOptionsAnnotationKey]] || [RNGoogleSignin application:application openURL:url sourceApplication:options[UIApplicationOpenURLOptionsSourceApplicationKey] annotation:options[UIApplicationOpenURLOptionsAnnotationKey]] || [[RNFirebaseLinks instance] application:application openURL:url options:options]; } - (BOOL)application:(UIApplication *)application continueUserActivity:(NSUserActivity *)userActivity restorationHandler:(void (^)(NSArray *))restorationHandler { return [[RNFirebaseLinks instance] application:application continueUserActivity:userActivity restorationHandler:restorationHandler]; } - (NSURL *)sourceURLForBridge:(RCTBridge *)bridge { #if DEBUG return [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index" fallbackResource:nil]; #else return [[NSBundle mainBundle] URLForResource:@"main" withExtension:@"jsbundle"]; #endif } @end ```


Android

Click To Expand

#### Have you converted to AndroidX? - [ ] 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 buildscript { ext { buildToolsVersion = "28.0.3" minSdkVersion = 16 compileSdkVersion = 28 targetSdkVersion = 28 supportLibVersion = "28.0.0" googlePlayServicesAuthVersion = "16.0.1" } repositories { mavenCentral() google() jcenter() } dependencies { classpath 'com.android.tools.build:gradle:3.4.1' classpath 'com.google.gms:google-services:4.2.0' // NOTE: Do not place your application dependencies here; they belong // in the individual module build.gradle files } } subprojects { afterEvaluate {project -> if (project.hasProperty("android")) { android { compileSdkVersion 28 buildToolsVersion "28.0.3" } } } } allprojects { repositories { google() mavenLocal() jcenter() maven { // All of React Native (JS, Obj-C sources, Android binaries) is installed from npm url "$rootDir/../node_modules/react-native/android" } maven { url 'https://maven.google.com' } } } ``` #### `android/app/build.gradle`: ```groovy project.ext.react = [ entryFile: "index.js" ] 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 = false android { compileSdkVersion rootProject.ext.compileSdkVersion compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 } defaultConfig { applicationId "com.example.myapp" minSdkVersion rootProject.ext.minSdkVersion targetSdkVersion rootProject.ext.targetSdkVersion versionCode 4 versionName "1.0.4" ndk { abiFilters "armeabi-v7a","arm64-v8a","x86","x86_64" } } splits { abi { reset() enable enableSeparateBuildPerCPUArchitecture universalApk false // If true, also generate a universal APK include "armeabi-v7a", "x86", "arm64-v8a", "x86_64" } } signingConfigs { release { if (project.hasProperty('MYAPP_RELEASE_STORE_FILE')) { storeFile file(MYAPP_RELEASE_STORE_FILE) storePassword MYAPP_RELEASE_STORE_PASSWORD keyAlias MYAPP_RELEASE_KEY_ALIAS keyPassword MYAPP_RELEASE_KEY_PASSWORD } } } buildTypes { release { minifyEnabled enableProguardInReleaseBuilds proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro" signingConfig signingConfigs.release } } // 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: // http://tools.android.com/tech-docs/new-build-system/user-guide/apk-splits 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 project(':react-native-gesture-handler') implementation project(':@react-native-community_async-storage') implementation project(':react-native-android-open-settings') implementation project(':react-native-device-info') implementation project(':react-native-cookies') implementation project(':react-native-google-signin') implementation project(':react-native-fbsdk') implementation project(':react-native-firebase') implementation project(':react-native-vector-icons') implementation project(':react-native-sound') implementation project(':react-native-linear-gradient') implementation project(':react-native-splash-screen') implementation fileTree(dir: "libs", include: ["*.jar"]) implementation "com.android.support:appcompat-v7:${rootProject.ext.supportLibVersion}" implementation(project(':react-native-geolocation-service')) { exclude group: 'com.google.android.gms', module: 'play-services-location' } implementation 'com.google.android.gms:play-services-location:16.0.0' implementation "com.facebook.react:react-native:+" // From node_modules implementation 'com.google.android.gms:play-services-base:16.1.0' implementation 'com.google.firebase:firebase-core:16.0.7' implementation 'com.google.firebase:firebase-analytics:16.3.0' implementation 'com.google.firebase:firebase-messaging:17.3.4' implementation 'com.google.firebase:firebase-config:16.3.0' implementation 'com.google.firebase:firebase-database:16.1.0' implementation 'com.google.firebase:firebase-invites:16.1.0' implementation 'me.leolin:ShortcutBadger:1.1.21@aar' implementation 'com.facebook.android:facebook-android-sdk:[4,5)' implementation 'com.google.android.gms:play-services-auth:16.0.1' implementation project(':react-native-splash-screen') } // 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 plugin: 'com.google.gms.google-services' ``` #### `android/settings.gradle`: ```groovy rootProject.name = 'MyApp' include ':react-native-gesture-handler' project(':react-native-gesture-handler').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-gesture-handler/android') include ':@react-native-community_async-storage' project(':@react-native-community_async-storage').projectDir = new File(rootProject.projectDir, '../node_modules/@react-native-community/async-storage/android') include ':react-native-android-open-settings' project(':react-native-android-open-settings').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-android-open-settings/android') include ':react-native-device-info' project(':react-native-device-info').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-device-info/android') include ':react-native-cookies' project(':react-native-cookies').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-cookies/android') include ':react-native-google-signin' project(':react-native-google-signin').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-google-signin/android') include ':react-native-fbsdk' project(':react-native-fbsdk').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-fbsdk/android') include ':react-native-firebase' project(':react-native-firebase').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-firebase/android') include ':react-native-vector-icons' project(':react-native-vector-icons').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-vector-icons/android') include ':react-native-geolocation-service' project(':react-native-geolocation-service').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-geolocation-service/android') include ':react-native-sound' project(':react-native-sound').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-sound/android') include ':react-native-linear-gradient' project(':react-native-linear-gradient').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-linear-gradient/android') include ':react-native-splash-screen' project(':react-native-splash-screen').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-splash-screen/android') include ':app' ``` #### `MainApplication.java`: ```java import android.app.Application; import com.facebook.react.ReactApplication; import com.swmansion.gesturehandler.react.RNGestureHandlerPackage; import com.reactnativecommunity.asyncstorage.AsyncStoragePackage; import com.levelasquez.androidopensettings.AndroidOpenSettingsPackage; import com.learnium.RNDeviceInfo.RNDeviceInfo; import com.psykar.cookiemanager.CookieManagerPackage; import co.apptailor.googlesignin.RNGoogleSigninPackage; import com.facebook.reactnative.androidsdk.FBSDKPackage; import io.invertase.firebase.RNFirebasePackage; import io.invertase.firebase.analytics.RNFirebaseAnalyticsPackage; import io.invertase.firebase.notifications.RNFirebaseNotificationsPackage; import io.invertase.firebase.messaging.RNFirebaseMessagingPackage; import io.invertase.firebase.config.RNFirebaseRemoteConfigPackage; import io.invertase.firebase.database.RNFirebaseDatabasePackage; import io.invertase.firebase.links.RNFirebaseLinksPackage; import com.oblador.vectoricons.VectorIconsPackage; import com.agontuk.RNFusedLocation.RNFusedLocationPackage; import com.zmxv.RNSound.RNSoundPackage; import com.BV.LinearGradient.LinearGradientPackage; import org.devio.rn.splashscreen.SplashScreenReactPackage; import com.facebook.react.ReactNativeHost; import com.facebook.react.ReactPackage; import com.facebook.react.shell.MainReactPackage; import com.facebook.soloader.SoLoader; import com.facebook.CallbackManager; import com.facebook.FacebookSdk; import com.facebook.appevents.AppEventsLogger; import java.util.Arrays; import java.util.List; public class MainApplication extends Application implements ReactApplication { private static CallbackManager mCallbackManager = CallbackManager.Factory.create(); protected static CallbackManager getCallbackManager() { return mCallbackManager; } private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) { @Override public boolean getUseDeveloperSupport() { return BuildConfig.DEBUG; } @Override protected List getPackages() { return Arrays.asList(new MainReactPackage(), new RNGestureHandlerPackage(), new AsyncStoragePackage(), new AndroidOpenSettingsPackage(), new RNDeviceInfo(), new CookieManagerPackage(), new RNGoogleSigninPackage(), new FBSDKPackage(mCallbackManager), new RNFirebasePackage(), new RNFirebaseAnalyticsPackage(), new RNFirebaseMessagingPackage(), new RNFusedLocationPackage(), new RNFirebaseNotificationsPackage(), new VectorIconsPackage(), new RNSoundPackage(), new LinearGradientPackage(), new SplashScreenReactPackage(), new RNFirebaseRemoteConfigPackage(), new RNFirebaseDatabasePackage(), new RNFirebaseLinksPackage()); } @Override protected String getJSMainModuleName() { return "index"; } }; @Override public ReactNativeHost getReactNativeHost() { return mReactNativeHost; } @Override public void onCreate() { super.onCreate(); AppEventsLogger.activateApp(this); SoLoader.init(this, /* native exopackage */ false); } } ``` #### `AndroidManifest.xml`: ```xml ```


Environment

Click To Expand

**`react-native info` output:** ``` React Native Environment Info: System: OS: macOS 10.14.5 CPU: (8) x64 Intel(R) Core(TM) i7-4870HQ CPU @ 2.50GHz Memory: 67.13 MB / 16.00 GB Shell: 5.3 - /bin/zsh Binaries: Node: 12.5.0 - /usr/local/bin/node Yarn: 1.16.0 - /usr/local/bin/yarn npm: 6.9.2 - /usr/local/bin/npm Watchman: 4.9.0 - /usr/local/bin/watchman SDKs: iOS SDK: Platforms: iOS 12.2, macOS 10.14, tvOS 12.2, watchOS 5.2 IDEs: Android Studio: 3.4 AI-183.6156.11.34.5522156 Xcode: 10.2.1/10E1001 - /usr/bin/xcodebuild npmPackages: react: 16.8.3 => 16.8.3 react-native: ^0.59.10 => 0.59.10 npmGlobalPackages: react-native-cli: 2.0.1 react-native-git-upgrade: 0.2.7 react-native-rename: 2.4.1 ``` - **Platform that you're experiencing the issue on**: - [ ] iOS - [ ] Android - [x] **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:** - `5.5.5` - **`Firebase` module(s) you're using that has the issue:** - `DynamicLinks` - **Are you using `TypeScript`?** - `No`


Think react-native-firebase is great? Please consider supporting all of the project maintainers and contributors by donating via our Open Collective where all contributors can submit expenses. [Learn More]

Base29 commented 5 years ago

Guys any suggestions on this ?

affanhashone commented 4 years ago

@Base29 Did You Got the Solution, I am having the same issue, its working in android, but in ios failed to created dynamic link

affanhashone commented 4 years ago

@Base29 Use REST API instead of creating dynamic link, I was having the same issue, now i am using Dynamic Link Rest API.

Hope This will help you

Base29 commented 4 years ago

@affanhashone ... yeah i ended up using the Dynamic Link API as well. Hopefully there will be a fix for it ...

affanhashone commented 4 years ago

@Base29 did you made This Working ON IOS, I had another issue "Dynamic Link Not Found "

Base29 commented 4 years ago

@affanhashone ... Yes it is working on iOS ... I created the Dynamic link like this ...

const dynamicLink = {
        dynamicLinkInfo: {
            domainUriPrefix: `https://${firebaseDynamicLinkPrefix}`,
            link: deepLink,
            androidInfo: {
                androidPackageName: identifier
            },
            iosInfo: {
                iosBundleId: identifier
            }
        },
        suffix: {
            option: 'SHORT'
        }
    };
affanhashone commented 4 years ago

@base29 See Below

"dynamicLinkInfo": {
"domainUriPrefix": "https://example.page.link", "link": https://example.page.link/${username}, "androidInfo": { "androidPackageName": "com.example" }, "iosInfo": { "iosBundleId": "com.beta.lexample" }, "socialMetaTagInfo": { "socialTitle": "ExampleSports", "socialDescription": "Example", "socialImageLink":imageUrl },

            },
            "suffix": {
                "option": "SHORT"
             }
affanhashone commented 4 years ago

@Base29 App Is install on TestFlight, Will it work ?

Base29 commented 4 years ago

@affanhashone ... yes it will work on testflight ...

affanhashone commented 4 years ago

@Base29 is it generating something like this (Short Link :) https://example.page.link/RTjlg

Base29 commented 4 years ago

@affanhashone ... Yes it is generating the short link with no issues what so ever ...

Base29 commented 4 years ago

@affanhashone ... Any suggestion on how to get data from the dynamic link ... it looks like this is not working

firebase
        .links()
        .getInitialLink()
        .then()
affanhashone commented 4 years ago

firebase.links() .getInitialLink() .then((url) => { if (url) { console.log("url",url) } else { console.log("Not Opened From the URL") } }); After getting the URL DO Whatever You Want!

Base29 commented 4 years ago

any idea how can I skip the preview page on iOS ? if I create the dynamic link manually I can pass a efr=1 query parameter in the link ... but I don't seem to find a argument that I can pass in my dynamic link object.

"dynamicLinkInfo": {
"domainUriPrefix": "https://example.page.link",
"link": https://example.page.link/${username},
"androidInfo": {
"androidPackageName": "com.example"
},
"iosInfo": {
"iosBundleId": "com.beta.lexample"
},
"socialMetaTagInfo": {
"socialTitle": "ExampleSports",
"socialDescription": "Example",
"socialImageLink":imageUrl
},

            },
            "suffix": {
                "option": "SHORT"
             }
stale[bot] commented 4 years ago

Hello 👋, to help manage issues we automatically close stale issues. This issue has been automatically marked as stale because it has not had activity for quite some time. Has this issue been fixed, or does it still require the community's attention?

This issue will be closed in 15 days if no further activity occurs. Thank you for your contributions.

stale[bot] commented 4 years ago

Closing this issue after a prolonged period of inactivity. If this is still present in the latest release, please feel free to create a new issue with up-to-date information.

Rahulkishanm commented 4 years ago

Hey the solution for this is add http or https in firebaseDynamicLinkPrefix