为什么Linking.getInitialURL总是返回null?

时间:2019-04-02 19:21:58

标签: ios react-native

我成功使用深层链接从共享扩展程序打开了我的应用程序。如果应用程序已经在运行,那么我将使用ComponentDidMount

Linking.addEventListener('url', this.handleOpenURL);中获取信息。

如果该应用尚未运行,我希望能够根据文档(https://facebook.github.io/react-native/docs/linking)使用Linking.getInitialURL();。除了它对我而言总是null以外。链接是打开我的应用程序的方式,但是无论如何,它都是null。我在App.js的componentDidMount中有该代码。

我正在使用本机59.2。

这是我的AppDelegate.m

#import "AppDelegate.h"

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

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
  NSURL *jsCodeLocation;

  jsCodeLocation = [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index" fallbackResource:nil];

  RCTRootView *rootView = [[RCTRootView alloc] initWithBundleURL:jsCodeLocation
                                                      moduleName:@"MYMODULENAME"
                                               initialProperties:nil
                                                   launchOptions:launchOptions];
  rootView.backgroundColor = [UIColor blackColor];

  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:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options
{
  return [RCTLinkingManager application:application openURL:url options:options];
}

- (BOOL)application:(UIApplication *)application continueUserActivity:(NSUserActivity *)userActivity
 restorationHandler:(void (^)(NSArray * _Nullable))restorationHandler
{
  return [RCTLinkingManager application:application
                   continueUserActivity:userActivity
                     restorationHandler:restorationHandler];
}

@end

如果该应用程序已经在后台运行,则getInitialURL()返回启动它的链接,否则我将返回null。我希望获得启动该应用程序的链接,即使它没有运行。

3 个答案:

答案 0 :(得分:0)

无法使getInitialURL()正常工作。但是,您可以使用:

Linking.addEventListener('url',(url)=>{ 
    console.log('this is the url: ',url);
});

这应该为您提供网址,请确保在componentWillUnmount()上注销该事件

我还尝试恢复到以前对我有用的react-native版本,但是仍然失败,所以很奇怪这个问题正在发生。

答案 1 :(得分:0)

如果我正在远程调试,响应总是null 。如果远程调试器已关闭,那么我将获得正确的URL。我无法使用console.log来使用警报进行确认。

答案 2 :(得分:0)

对于寻求快速修复的每个人,只需手动将 Linking.getInitialURL() 的结果与您的应用链接的值交换,例如:myapp://myhost

如果您不知道应该为本教程添加什么价值 https://blog.jscrambler.com/how-to-handle-deep-linking-in-a-react-native-app/