You need to enable JavaScript to run this app. Swift 5下短链接转完整URL的实现问题(适配Xcode 12.4)
优惠活动
大模型
产品
解决方案
定价
更多

Swift 5下短链接转完整URL的实现问题(适配Xcode 12.4)

问题核心原因

你现有代码存在两个关键问题:

  • 函数内部重写了传入的urlString参数,强制替换为全局的shortURL,导致入参失效
  • 仅读取urlResponse.url无法稳定获取多重重定向后的最终地址,部分短链服务对HEAD请求的响应逻辑和GET请求有差异,会返回不完整的重定向信息

修复后可运行代码

// 定义回调闭包,异步返回展开后的最终URL
func expandShortURL(_ shortURLString: String, completion: @escaping (URL?) -> Void) {
    guard let shortURL = URL(string: shortURLString) else {
        completion(nil)
        return
    }
    
    var request = URLRequest(url: shortURL)
    request.httpMethod = "HEAD"
    request.httpShouldHandleCookies = false
    request.timeoutInterval = 10
    
    URLSession.shared.dataTask(with: request) { _, response, error in
        // 先校验无错误、响应为标准HTTP响应
        guard error == nil, let httpResponse = response as? HTTPURLResponse else {
            completion(nil)
            return
        }
        // 重定向状态码范围:300~399,取Location头的跳转地址递归展开
        if (300...399).contains(httpResponse.statusCode), let redirectURL = httpResponse.allHeaderFields["Location"] as? String {
            expandShortURL(redirectURL, completion: completion)
        } else if httpResponse.statusCode == 200 {
            // 状态码200说明已经到达最终地址
            completion(httpResponse.url)
        } else {
            completion(nil)
        }
    }.resume()
}

// 调用示例
let testShortURL = "https://goo.gl/maps/MoaZNS825rpixfKu5"
expandShortURL(testShortURL) { finalURL in
    guard let finalURL = finalURL else {
        print("短链展开失败")
        return
    }
    print("展开后的完整URL: \(finalURL.absoluteString)")
}

兼容说明

  • 短链展开是异步网络操作,必须通过闭包回调获取结果,无法同步返回
  • 上述代码完全兼容Xcode 12.4对应的Swift版本,无需额外适配
  • 若遇到部分短链服务拒绝HEAD请求,可将request.httpMethod = "HEAD"修改为request.httpMethod = "GET",性能差异极小

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.11 10:18:00