React Native Linking url事件从不触发



当通过深度链接在模拟器中打开我的应用程序时,url事件永远不会触发。

请注意,getInitialurl在应用程序关闭时工作。但如果应用程序已经打开,并且我运行npx uri-scheme open "mychat://bar" --ios,应用程序会聚焦,但不会触发url事件。。。

有人有这个问题吗?

我正在运行XCode 13.4.1MacOS 12.5.1React Native 0.70

回购再现错误

在我的例子中,我在@interface AppDelegate下面添加了所需的AppDelegade代码块,但必须在接口下面的@implementation AppDelegae内部添加。

事件需要在AppDelegate.m文件中进行一些额外的配置,以便发出文档中提到的事件。从XCode打开您的项目并编辑AppDelegate.m,或者打开/ios/{YOUR_PROJECT_NAME}/AppDelegate.m(或AppDelegate.mim(文件,并在@end标记出现之前在文件末尾添加以下行:

// Add this inside `@implementation AppDelegate` above `@end`:
- (BOOL)application:(UIApplication *)application
openURL:(NSURL *)url
options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options
{
return [RCTLinkingManager application:application openURL:url options:options];
}
// Add this inside `@implementation AppDelegate` above `@end`:
- (BOOL)application:(UIApplication *)application continueUserActivity:(nonnull NSUserActivity *)userActivity
restorationHandler:(nonnull void (^)(NSArray<id<UIUserActivityRestoring>> * _Nullable))restorationHandler
{
return [RCTLinkingManager application:application
continueUserActivity:userActivity
restorationHandler:restorationHandler];
}
@end 

重要信息:如果你能做到这一点,你有两种处理深度链接事件的方法,你必须分别处理它们!我认为第二个会帮助你解决你的问题。

1-应用程序已关闭,将通过深度链接打开:

Linking.getInitialURL().then(url => { 
if(url != null) {
//DoSomethingWithUrl
}
});

2-该应用程序已经在运行,并将使用深度链接进行聚焦:

Linking.addEventListener('url',(url)=>{ 
if(url != null) {
//DoSomethingWithUrl
}
});

将这些行放在应用程序视图中,并假设你的应用程序具有某种状态(例如使用useState钩子或redux(,它会在每次发生状态更改时调用,因为状态本身之外的所有内容都会在更改状态时重新呈现。因此,我建议您在应用程序启动时只调用这两种方法一次,这样做可以实现:

const [isInitialStart, setInitialStart] = useState(true);
if(isInitialStart){
Linking.getInitialURL().then(url => { 
if(url != null) {
//DoSomethingWithUrl
}
});
Linking.addEventListener('url',(url)=>{ 
if(url != null) {
//DoSomethingWithUrl
}
});
setInitialStart(false); 
}

我希望这能帮助你解决你的问题。

如果使用react native +0.71

AppDelegate.m更改为AppDelegate.mm

// Add the header at the top of the file:
#import <React/RCTLinkingManager.h>
// Add this inside `@implementation AppDelegate` above `@end`:
- (BOOL)application:(UIApplication *)application
openURL:(NSURL *)url
options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options
{
return [RCTLinkingManager application:application openURL:url options:options];
}
// Add this inside `@implementation AppDelegate` above `@end`:
- (BOOL)application:(UIApplication *)application continueUserActivity:(nonnull NSUserActivity *)userActivity
restorationHandler:(nonnull void (^)(NSArray<id<UIUserActivityRestoring>> * _Nullable))restorationHandler
{
return [RCTLinkingManager application:application
continueUserActivity:userActivity
restorationHandler:restorationHandler];
}

最新更新