You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

iOS:如何通过默认浏览器与搜索引擎发起网页搜索(URL Scheme需求)

在iOS中调用系统默认浏览器和搜索引擎执行搜索的方案
  • 放弃使用x-web-search://这个Scheme,它仅会唤起Safari,无法适配用户设置的默认浏览器。

  • 正确的实现思路是:构造用户系统默认搜索引擎的搜索URL,再通过系统API打开该URL,系统会自动调用用户设置的默认浏览器加载搜索结果。

  • 具体步骤:

    1. 获取系统默认搜索引擎的标识:通过NSUserDefaults读取DefaultSearchProviderIdentifier字段,该字段对应的值是类似com.apple.Safari.Google、com.apple.Safari.DuckDuckGo这样的标识符。
    2. 根据标识符匹配对应的搜索URL模板:
      • com.apple.Safari.Google → https://www.google.com/search?q=
      • com.apple.Safari.Bing → https://www.bing.com/search?q=
      • com.apple.Safari.Yahoo → https://search.yahoo.com/search?p=
      • com.apple.Safari.DuckDuckGo → https://duckduckgo.com/?q=
    3. 对搜索关键词做URL编码:使用addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)处理关键词,避免特殊字符破坏URL结构。
    4. 拼接编码后的关键词到搜索模板,生成完整URL,再调用UIApplication.shared.open(_:options:completionHandler:)打开该URL。
  • 示例代码片段:

func openSystemSearch(with query: String) {
    guard let defaults = UserDefaults(suiteName: "com.apple.mobile.internetsearch"),
          let providerId = defaults.string(forKey: "DefaultSearchProviderIdentifier"),
          let encodedQuery = query.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) else {
        // 若获取失败则使用默认搜索引擎兜底
        if let url = URL(string: "https://www.google.com/search?q=\(encodedQuery ?? "")") {
            UIApplication.shared.open(url)
        }
        return
    }
    
    var searchTemplate = ""
    switch providerId {
    case "com.apple.Safari.Google":
        searchTemplate = "https://www.google.com/search?q="
    case "com.apple.Safari.Bing":
        searchTemplate = "https://www.bing.com/search?q="
    case "com.apple.Safari.Yahoo":
        searchTemplate = "https://search.yahoo.com/search?p="
    case "com.apple.Safari.DuckDuckGo":
        searchTemplate = "https://duckduckgo.com/?q="
    default:
        searchTemplate = "https://www.google.com/search?q="
    }
    
    if let searchUrl = URL(string: searchTemplate + encodedQuery) {
        UIApplication.shared.open(searchUrl)
    }
}

内容的提问来源于stack exchange,提问作者performat

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.22 15:10:03