【问题标题】:canOpenURL returning true for custom URL scheme even if app is not installed即使未安装应用程序,canOpenURL 也会为自定义 URL 方案返回 true
【发布时间】:2016-03-13 00:03:44
【问题描述】:
 NSString *customURL = @"mycustomurl://"; 

 if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:customURL]]) {
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:customURL]];
 } else {
    ...
 }

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

【问题讨论】:

标签: ios objective-c url-scheme


【解决方案1】:

这是我用来打开优步应用程序的工具,如果安装了它,则打开优步网站

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

像这样(其中包含了应用程序uber和twitter的名称)info.plist screenshot

【讨论】:

    【解决方案2】:

    如果使用 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 字段中输入应用程序方案 url 字符串,然后按 enter。从结果中总结出如何进行。

    【讨论】:

    • 感谢回复,应用中指定了LSApplicationQueriesScheme。输入其中指定的 URL 以外的 URL 会导致 canOpenURL 为“否”。是的,目标应用方案之前已安装在 SIM 卡和手机上。
    • @stuart_gunn 再次尝试重启设备。
    • @stuart_gunn 如果您在设备中打开 safari 浏览器应用程序,然后在 url 字段 (appscheme://) 中输入应用程序方案 url 字符串,按回车,它会打开应用程序吗?
    • Sooooo 原来是为两个应用程序注册了 URL 方案 - 调用者和被调用者。在 Safari 中输入方案打开了错误的应用程序。谢谢你的帮助。感觉有点傻。
    【解决方案3】:

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

    它仅适用于 LSApplicationQueriesSchemes

    这将不起作用

    这将工作

    【讨论】:

    • 这是我的问题,谢谢你提到它。花了我 1 小时,
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-06-24
    • 1970-01-01
    • 2016-03-23
    • 1970-01-01
    • 2012-01-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多