Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Launch URL is not working #1350

Closed
pilotpirxie opened this issue Jan 23, 2022 · 2 comments
Closed

Launch URL is not working #1350

pilotpirxie opened this issue Jan 23, 2022 · 2 comments

Comments

@pilotpirxie
Copy link

pilotpirxie commented Jan 23, 2022

Description:
Hi, launch_url seems not working. I followed the tutorials:
https://documentation.onesignal.com/docs/react-native-sdk-setup
https://documentation.onesignal.com/docs/links
https://nbiscan7.medium.com/how-to-deep-link-in-react-native-4c8262f3154d

Push notification is opening the app on the iOS but it's not calling a function with launch_url/deep link. On Android, I had even a problem with the opening applications. I tried to use both emulators and real devices. Android is getting push notifications but after tap, nothing is happening.

My current AndroidManifest.xml:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
  package="com.company.appname">

    <uses-permission android:name="android.permission.INTERNET" />

    <application
      android:name=".MainApplication"
      android:label="@string/app_name"
      android:icon="@mipmap/ic_launcher"
      android:roundIcon="@mipmap/ic_launcher_round"
      android:allowBackup="false"
      android:theme="@style/AppTheme">
      <activity
        android:name=".MainActivity"
        android:label="@string/app_name"
        android:configChanges="keyboard|keyboardHidden|orientation|screenSize|uiMode"
        android:launchMode="singleTask"
        android:windowSoftInputMode="adjustResize">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
        <intent-filter>
          <action android:name="android.intent.action.VIEW" />
          <category android:name="android.intent.category.DEFAULT" />
          <category android:name="android.intent.category.BROWSABLE" />
          <data android:scheme="appname" />
        </intent-filter>
      </activity>
      <activity android:name="com.facebook.react.devsupport.DevSettingsActivity" />
      <meta-data android:name="com.facebook.sdk.ApplicationId" android:value="@string/facebook_app_id"/>
      <meta-data android:name="com.facebook.sdk.ClientToken" android:value="@string/facebook_client_token"/>
      <meta-data android:name="com.onesignal.suppressLaunchURLs" android:value="true"/>
    </application>
</manifest>

Info.plist:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
	<key>CFBundleDevelopmentRegion</key>
	<string>en</string>
	<key>CFBundleDisplayName</key>
	<string>appName</string>
	<key>CFBundleExecutable</key>
	<string>$(EXECUTABLE_NAME)</string>
	<key>CFBundleIdentifier</key>
	<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
	<key>CFBundleInfoDictionaryVersion</key>
	<string>6.0</string>
	<key>CFBundleName</key>
	<string>$(PRODUCT_NAME)</string>
	<key>CFBundlePackageType</key>
	<string>APPL</string>
	<key>CFBundleShortVersionString</key>
	<string>1.0</string>
	<key>CFBundleSignature</key>
	<string>????</string>
	<key>CFBundleURLTypes</key>
	<array>
		<dict>
			<key>CFBundleTypeRole</key>
			<string>Editor</string>
			<key>CFBundleURLName</key>
			<string>fb938655976760241</string>
			<key>CFBundleURLSchemes</key>
			<array>
				<string>fb -- fbid --</string>
			</array>
		</dict>
		<dict>
			<key>CFBundleTypeRole</key>
			<string>Editor</string>
			<key>CFBundleURLName</key>
			<string>appName</string>
			<key>CFBundleURLSchemes</key>
			<array>
				<string>appName</string>
			</array>
		</dict>
	</array>
	<key>CFBundleVersion</key>
	<string>$(CURRENT_PROJECT_VERSION)</string>
	<key>FacebookAppID</key>
	<string> -- my fb id --</string>
	<key>FacebookDisplayName</key>
	<string>appName</string>
	<key>ITSAppUsesNonExemptEncryption</key>
	<false/>
	<key>LSApplicationQueriesSchemes</key>
	<array>
		<string>fbapi</string>
		<string>fb-messenger-api</string>
		<string>fbauth2</string>
		<string>fbshareextension</string>
	</array>
	<key>LSRequiresIPhoneOS</key>
	<true/>
	<key>NSAppTransportSecurity</key>
	<dict>
		<key>NSAllowsArbitraryLoads</key>
		<true/>
		<key>NSExceptionDomains</key>
		<dict>
			<key>localhost</key>
			<dict>
				<key>NSExceptionAllowsInsecureHTTPLoads</key>
				<true/>
			</dict>
		</dict>
	</dict>
	<key>NSLocationWhenInUseUsageDescription</key>
	<string></string>
	<key>OneSignal_suppress_launch_urls</key>
	<true/>
	<key>UIBackgroundModes</key>
	<array>
		<string>remote-notification</string>
	</array>
	<key>UILaunchStoryboardName</key>
	<string>LaunchScreen</string>
	<key>UIMainStoryboardFile</key>
	<string>LaunchScreen</string>
	<key>UIRequiredDeviceCapabilities</key>
	<array>
		<string>armv7</string>
	</array>
	<key>UISupportedInterfaceOrientations</key>
	<array>
		<string>UIInterfaceOrientationPortrait</string>
		<string>UIInterfaceOrientationLandscapeLeft</string>
		<string>UIInterfaceOrientationLandscapeRight</string>
	</array>
	<key>UIViewControllerBasedStatusBarAppearance</key>
	<false/>
</dict>
</plist>

Podfile:


require_relative '../node_modules/react-native/scripts/react_native_pods'
require_relative '../node_modules/@react-native-community/cli-platform-ios/native_modules'

platform :ios, '11.0'

target 'appName' do
  config = use_native_modules!

  use_react_native!(
    :path => config[:reactNativePath],
    # to enable hermes on iOS, change `false` to `true` and then install pods
    :hermes_enabled => false
  )


  target 'appNameTests' do
    inherit! :complete
    # Pods for testing
  end

  # Enables Flipper.
  #
  # Note that if you have use_frameworks! enabled, Flipper will not work and
  # you should disable the next line.
  use_flipper!()

  post_install do |installer|
    react_native_post_install(installer)
    __apply_Xcode_12_5_M1_post_install_workaround(installer)
  end
end

target 'OneSignalNotificationServiceExtension' do
  pod 'OneSignalXCFramework', '>= 3.0', '< 4.0'
end

AppDelegate.m

#import "AppDelegate.h"

#import <React/RCTBridge.h>
#import <React/RCTBundleURLProvider.h>
#import <React/RCTRootView.h>
#import <FBSDKCoreKit/FBSDKCoreKit.h>
#import <React/RCTLinkingManager.h>

#ifdef FB_SONARKIT_ENABLED
#import <FlipperKit/FlipperClient.h>
#import <FlipperKitLayoutPlugin/FlipperKitLayoutPlugin.h>
#import <FlipperKitUserDefaultsPlugin/FKUserDefaultsPlugin.h>
#import <FlipperKitNetworkPlugin/FlipperKitNetworkPlugin.h>
#import <SKIOSNetworkPlugin/SKIOSNetworkAdapter.h>
#import <FlipperKitReactPlugin/FlipperKitReactPlugin.h>

static void InitializeFlipper(UIApplication *application) {
  FlipperClient *client = [FlipperClient sharedClient];
  SKDescriptorMapper *layoutDescriptorMapper = [[SKDescriptorMapper alloc] initWithDefaults];
  [client addPlugin:[[FlipperKitLayoutPlugin alloc] initWithRootNode:application withDescriptorMapper:layoutDescriptorMapper]];
  [client addPlugin:[[FKUserDefaultsPlugin alloc] initWithSuiteName:nil]];
  [client addPlugin:[FlipperKitReactPlugin new]];
  [client addPlugin:[[FlipperKitNetworkPlugin alloc] initWithNetworkAdapter:[SKIOSNetworkAdapter new]]];
  [client start];
}
#endif

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
#ifdef FB_SONARKIT_ENABLED
  InitializeFlipper(application);
#endif

    [[FBSDKApplicationDelegate sharedInstance] application:application
                             didFinishLaunchingWithOptions:launchOptions];

  RCTBridge *bridge = [[RCTBridge alloc] initWithDelegate:self launchOptions:launchOptions];
  RCTRootView *rootView = [[RCTRootView alloc] initWithBridge:bridge
                                                   moduleName:@"appName"
                                            initialProperties:nil];

  if (@available(iOS 13.0, *)) {
      rootView.backgroundColor = [UIColor systemBackgroundColor];
  } else {
      rootView.backgroundColor = [UIColor whiteColor];
  }

  self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
  UIViewController *rootViewController = [UIViewController new];
  rootViewController.view = rootView;
  self.window.rootViewController = rootViewController;
  [self.window makeKeyAndVisible];
  return YES;
}

- (BOOL)application:(UIApplication *)application
            openURL:(NSURL *)url
            options:(nonnull NSDictionary<UIApplicationOpenURLOptionsKey, id> *)options
{
  if ([[FBSDKApplicationDelegate sharedInstance] application:application openURL:url options:options]) {
    return YES;
  }

  return [RCTLinkingManager application:application openURL:url options:options];
}

- (NSURL *)sourceURLForBridge:(RCTBridge *)bridge
{
#if DEBUG
  return [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index" fallbackResource:nil];
#else
  return [[NSBundle mainBundle] URLForResource:@"main" withExtension:@"jsbundle"];
#endif
}

@end

And the component where I connected onesignal:

// config
export default {
  LAUNCH_SCHEMA: 'appName://',
};


// component
  const handleOpenNotification = (event: OpenedEvent) => {
    try {
      if (!event?.notification?.launchURL) {
        return;
      }

      const launchURL = event?.notification?.launchURL;
      if (launchURL.indexOf(config.LAUNCH_SCHEMA) === 0) {
        const screenToNavigate = launchURL.split(config.LAUNCH_SCHEMA)[1];

        if (screenToNavigate.split('/').length !== 2) {
          return;
        }

        const screen = screenToNavigate.split('/')[0];
        const entityId = screenToNavigate.split('/')[1];

        if (screen === 'screen1') {
          navigate('Screen1', {});
        } else if (screen === 'screen2') {
          navigate('Screen2', {id: entityId});
        }
      }
    } catch (e) {
      console.log(e);
    }
  };

  useEffect(() => {
    OneSignal.setAppId('-- my app id here -- ');
    OneSignal.promptForPushNotificationsWithUserResponse(
      (response: boolean) => {
        console.log('User response', response);
      },
    );
    OneSignal.setNotificationOpenedHandler(handleOpenNotification);
  }, []);

But still it's not working :<

Environment

{
  "name": "appName",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "android": "react-native run-android",
    "ios": "react-native run-ios",
    "start": "react-native start",
    "test": "jest",
    "lint": "eslint . --ext .js,.jsx,.ts,.tsx"
  },
  "dependencies": {
    "@invertase/react-native-apple-authentication": "^2.1.5",
    "@react-native-async-storage/async-storage": "^1.15.14",
    "@react-native-clipboard/clipboard": "^1.9.0",
    "@react-native-masked-view/masked-view": "^0.2.6",
    "@react-navigation/elements": "^1.2.1",
    "@react-navigation/native": "^6.0.6",
    "@react-navigation/stack": "^6.0.11",
    "axios": "^0.24.0",
    "moment": "^2.29.1",
    "react": "17.0.2",
    "react-native": "0.66.4",
    "react-native-fbsdk-next": "^6.2.0",
    "react-native-gesture-handler": "^2.1.0",
    "react-native-onesignal": "^4.3.5",
    "react-native-safe-area-context": "^3.3.2",
    "react-native-screens": "^3.10.1",
    "react-native-snap-carousel": "^3.9.1",
    "react-native-splash-screen": "^3.3.0",
    "react-redux": "^7.2.6",
    "redux": "^4.1.2",
    "redux-devtools-extension": "^2.13.9",
    "redux-saga": "^1.1.3"
  },
  "devDependencies": {
    "@babel/core": "^7.12.9",
    "@babel/runtime": "^7.12.5",
    "@react-native-community/eslint-config": "^2.0.0",
    "@types/jest": "^26.0.23",
    "@types/react-native": "^0.66.4",
    "@types/react-native-snap-carousel": "^3.8.5",
    "@types/react-redux": "^7.1.21",
    "@types/react-test-renderer": "^17.0.1",
    "@typescript-eslint/eslint-plugin": "^5.7.0",
    "@typescript-eslint/parser": "^5.7.0",
    "babel-jest": "^26.6.3",
    "eslint": "^7.14.0",
    "jest": "^26.6.3",
    "metro-react-native-babel-preset": "^0.66.2",
    "react-test-renderer": "17.0.2",
    "typescript": "^4.4.4"
  },
  "resolutions": {
    "@types/react": "^17"
  },
  "jest": {
    "preset": "react-native",
    "moduleFileExtensions": [
      "ts",
      "tsx",
      "js",
      "jsx",
      "json",
      "node"
    ]
  }
}

Project Format: Xcode 12.0-compatible
iPhone XR with iOS 15.1
Android Xiaomi Pocophone F1 with MIUI Global 12.0.3/Android 12.0.3

Steps to Reproduce Issue:
Follow the tutorials on the fresh app, set files as above and send a notification with appName://screen2/123 launch url.

@pilotpirxie
Copy link
Author

pilotpirxie commented Jan 24, 2022

Nevermind, I found what was the issue at least with the launcher URL.

I have been initializing onesignal like this:

  useEffect(() => {
    OneSignal.setAppId('-- my app id here -- ');
    OneSignal.promptForPushNotificationsWithUserResponse(
      (response: boolean) => {
        console.log('User response', response);
      },
    );
    OneSignal.setNotificationOpenedHandler(handleOpenNotification);
  }, []);

And it was working, but the handleOpenNotification was using navigate and navigatorRef props (from react-navigation library) but at the moment of execution of the callback ref was not available so it looked like the launch URL was not passed down the app while launching.

Still, I have a problem with android, after clicking on the notification application is not open. I have to open it manually. I found in the application setting "Display pop-up windows while running in the background" is helpful. https://stackoverflow.com/questions/59645936/displaying-popup-windows-while-running-in-the-background

https://stackoverflow.com/questions/59418504/xiaomi-devices-permission-to-enable-apps-pop-up-windows-while-running-in-the-bac

This permission is added automatically by Google Play and isn't granted on local builds, not even release builds

if you target SDK version 30 and compile with 30, Google Play will give you the permission

compileSdkVersion 30
targetSdkVersion 30

note: I targeted 28 and it didn't work for me

As far as I see it's the problem rather with Xiaomi miui (their custom android firmware) than onesignal or react-native so I'm closing the issue.

@SulaimanAlbulaihy
Copy link

@pilotpirxie hello, how did you manage to fix it
I have OneSignal.setNotificationOpenedHandler(handleOpenNotification)
in useEffect, and navigationRef to navigate but it's not working in ios/android

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants