即使未安装app,canOpenURL也会返回true以用于自定义URL方案

NSString *customURL = @"mycustomurl://"; if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:customURL]]) { [[UIApplication sharedApplication] openURL:[NSURL URLWithString:customURL]]; } else { ... } 

即使未安装公开自定义URL的目标应用程序,该应用程序也会为“canOpenURL”返回true。 手机和模拟器上都会出现此问题。 openURL然后默默地失败。 任何想法为什么会发生/如何捕捉这种情况?

如果使用SDK 9.0及更高版本的应用程序,那么您必须确保在主应用程序的info.plist中添加要打开的应用程序方案:

在此处输入图像描述

如果不将上述内容添加到主应用程序的info.plist(相应地更改方案),canOpenURL将始终返回NO。 除非使用iOS SDK低于9.0的应用程序,否则不会发生。

另外,使用以下逻辑,因为它更安全:

 NSString * urlStr = @"mycustomurl://"; NSURL * url = [NSURL URLWithString:urlStr]; if ([[UIApplication sharedApplication] canOpenURL:url]) { if([[UIApplication sharedApplication] openURL:url]) { // App opened } else { // App not opened } } else { // Can not open URL } 

最后一次检查我建议在设备中打开Safari应用程序,在url字段中输入app scheme url string,按回车键。 从结果中得出结论如何进行。

确保您使用的是URL类型的 LSApplicationQueriesSchemes

它仅适用于LSApplicationQueriesSchemes

不行

网址类型

这会奏效

LSApplicationQueriesSchemes

这是我用来打开优步应用程序,如果它安装了其他开放的优步网站

 if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"uber://"]]) { //Uber is installed [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"uber://"]]; } else { [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"https://uber.com"]]; } 

不要忘记在info.plist文件中添加此LSApplicationQueriesSchemes

像这样(app uber和twitter的名字已包含在此内容) info.plist截图