首页 > 解决方案 > 使用添加的 url 方案时,Urls 不会打开

问题描述

我想用谷歌浏览器打开网址。如果我用 'googlechrome://' 替换 url 前缀,这很好用(ergo google chrome 打开 url)。

但是,我还想检查是否安装了我正在使用“canOpenUrl”方法的chrome,我再次明白我需要确保添加了相应的url方案。到目前为止一切顺利,我在我的 plist 中的 url 方案中添加了“googlechrome”和“googlechromes”,并且“canOpenUrl”方法返回为真。但是没有任何反应,谷歌浏览器根本无法打开。有什么明显的我失踪了吗?

这段代码工作得很好,谷歌浏览器打开了很长时间,我的 plist 中没有任何 url 方案:

if let googleUrl = URL(string: "googlechrome" + "\(urlString.replaceStringPrefix())") {
    print("openUrl, googleUrl: ", googleUrl)
    UIApplication.shared.open(googleUrl, options: [:])
}

以下为 canOpenUrl 与相应的 plist 条目返回 true,但没有任何反应,Google chrome 不会打开:

<key>CFBundleURLSchemes</key>
    <array>
        <string>googlechrome</string>
        <string>googlechromes</string>
        <string>googlechrome-x-callback</string>
    </array>



if let googleUrl = URL(string: "googlechrome" + "\(urlString.replaceStringPrefix())") {
     print("openUrl, googleUrl: ", googleUrl)
     if UIApplication.shared.canOpenURL(googleUrl) {
           print("Can open url with Chrome, url: ", googleUrl)
           UIApplication.shared.open(googleUrl, options: [:])
     } else {
           print("Cannot open url with Chrome, falling back to Safari")
           if let safariUrl = URL(string: urlString) {
                UIApplication.shared.open(safariUrl, options: [:])
           }
     }
 }

标签: swiftgoogle-chromeurlplist

解决方案


找到了罪魁祸首。canOpenUrl 将使用上面的 plist 条目返回 true,在各个应用程序中实际打开的正确键是 LSApplicationQueriesSchemes,结果如下:

        <key>LSApplicationQueriesSchemes</key>
        <array>
            <string>googlechrome</string>
            <string>googlechromes</string>
            <string>googlechrome-x-callback</string>
        </array>

推荐阅读