You need to enable JavaScript to run this app. Swift中使用URLComponents无法生成正确URL?Unsplash API调用问题
优惠活动
大模型
产品
解决方案
定价
更多

Swift中使用URLComponents无法生成正确URL?Unsplash API调用问题

存在的配置问题

  • path属性错误混入查询参数内容
    URLComponents的设计逻辑是严格拆分URL的各组成字段(scheme、host、path、query等),各字段独立赋值,不能跨字段拼接内容。其中path仅需填写接口的纯路径部分,不能携带?起始的查询串片段。你当前写入的search/photos?per_page=20会被系统完整识别为路径的一部分,完全破坏URL的结构规则,正确的path值仅为search/photos。
  • queryItems配置存在多处错误和遗漏
    1. 遗漏独立的per_page查询参数,该参数本就属于查询项范畴,不该被硬塞到path字段中
    2. 本应对应query=london的参数被错误配置为空名称的项:你把参数名写成了空字符串,实际该查询项的参数名为query,值为london
    3. 未遵循“所有查询参数统一交由queryItems管理”的原则,反而手动拼接参数到path里,会失去URLComponents自动做特殊字符转义、编码的能力。
  • 补充:你提到的目标地址中per_page=20;query=london里的分号属于输入笔误,标准URL的查询参数间分隔符为&,URLComponents生成合法URL时会自动使用正确分隔符拼接参数,无需手动拼接。

修正后的代码

func fetchNews() {
    var urlComponents = URLComponents()
    urlComponents.scheme = "https"
    urlComponents.host = "api.unsplash.com"
    // 填写纯路径,不携带任何查询参数
    urlComponents.path = "search/photos"
    // 所有查询参数统一在queryItems中配置
    urlComponents.queryItems = [
        .init(name: "per_page", value: "20"),
        .init(name: "query", value: "london"),
        .init(name: "client_id", value: "cn-xTwbvpcPUcpOgwJ2WIehB8UB641vs6GasCGMurzI")
    ]
    
    if let url = urlComponents.url {
        performRequest(url)
        print(url)
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.12 14:27:09