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

Swift如何从deeplink中提取跳转目标URL?

从deeplink提取目标URL的最优实现方案

以下是两种适配不同场景的稳妥实现,均可以稳定拿到你需要的目标URL:

方案1:通用场景(兼容URL编码、结构波动)

基于系统URLComponents实现,自动处理特殊字符,无需手动处理URL结构细节:

guard let deeplinkUrl = URL(string: "myapp://open-browser/https://mydaily.dev/JOURNAL/home?id=123e4567-e89b-12d3-a456-426655440000&source=01&channel_id=HOME"),
      let components = URLComponents(url: deeplinkUrl, resolvingAgainstBaseURL: false) else {
    // 此处替换为你的无效链接兜底逻辑
    fatalError("无效deeplink")
}

// 移除path开头的默认斜杠
let purePath = components.path.hasPrefix("/") ? String(components.path.dropFirst()) : components.path
// 拼接query参数
let targetUrlStr = components.query.map { "\(purePath)?\($0)" } ?? purePath

// 输出结果符合预期
print(targetUrlStr)

方案2:固定前缀场景(性能最优)

如果你的业务里deeplink前缀完全固定为myapp://open-browser/,直接截取字符串即可,没有多余的解析开销:

let deeplinkStr = "myapp://open-browser/https://mydaily.dev/JOURNAL/home?id=123e4567-e89b-12d3-a456-426655440000&source=01&channel_id=HOME"
let fixedPrefix = "myapp://open-browser/"

if deeplinkStr.hasPrefix(fixedPrefix) {
    let targetUrlStr = String(deeplinkStr.dropFirst(fixedPrefix.count))
    print(targetUrlStr)
}

方案优势

相比手动拼接path和query的实现,以上方案:

  • 自动处理URL编码特殊字符,不会出现拼接错误
  • 逻辑简洁,维护成本低
  • 可根据业务场景灵活选择,性能和通用性兼顾

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 23:45:04