【问题标题】:How to launch chrome browser while opening a link in iOS objective c如何在 iOS 目标 c 中打开链接时启动 chrome 浏览器
【发布时间】:2026-01-19 03:40:01
【问题描述】:

这是我的代码,

如何只通过chrome浏览器打开链接?

NSString* url = @"some url";

NSURL *inputURL = [NSURL URLWithString:url];
NSString *scheme = inputURL.scheme;

// Replace the URL Scheme with the Chrome equivalent.
NSString *chromeScheme = nil;
if ([scheme isEqualToString:@"http"]) {
    chromeScheme = @"googlechrome";
} else if ([scheme isEqualToString:@"https"]) {
    chromeScheme = @"googlechromes";
}

// Proceed only if a valid Google Chrome URI Scheme is available.
if (chromeScheme) {
    NSString *absoluteString = [inputURL absoluteString];
    NSRange rangeForScheme = [absoluteString rangeOfString:@":"];
    NSString *urlNoScheme =
    [absoluteString substringFromIndex:rangeForScheme.location];
    NSString *chromeURLString =
    [chromeScheme stringByAppendingString:urlNoScheme];
    NSURL *chromeURL = [NSURL URLWithString:chromeURLString];

    // Open the URL with Chrome.
    [[UIApplication sharedApplication] openURL:chromeURL];
}

我什至在.plist中添加了以下内容,

<key>LSApplicationQueriesSchemes</key>
    <array>
        <string>googlechrome</string>
    </array>

但还是不行。

【问题讨论】:

  • LSApplicationQueriesSchemes 中,您声明了 googlechrome,但未包含变体 googlechromes
  • 在此处找到类似解决方案的类似问题:*.com/questions/34149611/…

标签: ios objective-c google-chrome nsurl launch


【解决方案1】:

首先确保您已在测试 iPhone 设备中安装了 Google Chrome 浏览器应用程序。如果您在模拟器中测试此代码,那么它将无法正常工作,因为 Google Chrome 浏览器应用程序无法安装在 Xcode 模拟器中。在 iPhone 设备上您可以通过以下方式检查 chrome 应用程序的安装

//Check if Google Chrome is Instaled
    if ([[UIApplication sharedApplication] canOpenURL:chromeURL]) {

        //open URL in Google chrome browser app
        [[UIApplication sharedApplication] openURL:chromeURL];
    }
    else
    {
        //Remove Google Chrome Scheme  at start of application and open link     in safari append http or https at start
         [[UIApplication sharedApplication] openURL:safariURL];

    }

您的代码运行良好

Code Spinet

结果一

Screeen Demo

在跑步形式中的应用

Final Result

【讨论】:

  • 好的.. 非常感谢
  • 我认为这个答案不太正确。苹果文档非常清楚使用canOpenURL:时需要LSApplicationQueriesSchemes来自文档:If your app is linked on or after iOS 9.0, you must declare the URL schemes you want to pass to this method. Do this by adding the LSApplicationQueriesSchemes key to your app's Info.plist file.
  • 是的,你是对的。对于 canOpenURL,我们需要根据 Apple 文档在 info plist 文件中添加密钥。实际上,即使在 iOS 11 上,我实际上也测试了上面的代码,但没有添加该密钥,这也可以正常工作。我已经更新了答案,感谢您的指正。
  • 在 Xcode 11.5 和 swift 5 中我该怎么做? @HafizShahzadAli
最近更新 更多