处理 URL 方案 react-native 和 Swift

Hur*_*aki 6 javascript xcode ios swift react-native

我想在我的本机应用程序中处理自定义 URL 方案。因此,我首先在我的根组件中的 JS 代码中添加了一个 eventListener,如下所示:

componentDidMount() {
    Linking.addEventListener('url', this.handleOpenURL);
}

componentWillUnmount() {
    Linking.removeEventListener('url', this.handleOpenURL);
}

handleOpenURL = event => {
    console.log('event', event);
};
Run Code Online (Sandbox Code Playgroud)

在我的 Xcode 应用程序中,我添加了一个自定义 URL 方案“com.myScheme”。

当我尝试在 AppDelegate.swift 中添加函数来处理深层链接时,出现了我的问题。

这是我的功能:

func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey: Any] = [:]) -> Bool {
    print(url)
    return true
}
Run Code Online (Sandbox Code Playgroud)

似乎 return true 不足以在我的应用程序中触发我的监听器......

我知道 react-native 文档中有一个 Objective-C 方法:

#import <React/RCTLinkingManager.h>

- (BOOL)application:(UIApplication *)application
   openURL:(NSURL *)url
   options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options
{
  return [RCTLinkingManager application:application openURL:url options:options];
}
Run Code Online (Sandbox Code Playgroud)

但是我只想在我的项目中使用 Swift 来提高我在这门语言上的技能。问题是我找不到任何使用 Swift 实现的函数示​​例。

这就是为什么我需要一些帮助来实现这个方法,然后在我的 RN 应用程序中触发我的事件。

感谢您的理解 :)

小智 5

关于你的 AppDelegate 方法,swift 版本应该是:

public func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {
    return RCTLinkingManager.application(app, open: url, options: options)
}
Run Code Online (Sandbox Code Playgroud)

  • 我的意思是你应该已经在你的顶级文件中导入了 React 包“import React”。并且不要忘记在 Bridging-Header.h `#import « React/RCTLinkingManager.h » 中导入。 (4认同)