如何在Swift中将http转换为https URL?

iKK*_*iKK -3 url https swift

使用Swift4 - 你如何转换http://www.myWebsite.comhttps://www.myWebsite.com

请注意小细节:http vs. http s

rma*_*ddy 6

假设您正在使用字符串,您可以使用简单的文本替换:

let http = "http://some.com/example.html"
let https = "https" + http.dropFirst(4)
Run Code Online (Sandbox Code Playgroud)

或者您可以使用URLComponents:

let http = "http://some.com/example.html"
var comps = URLComponents(string: http)!
comps.scheme = "https"
let https = comps.string!
Run Code Online (Sandbox Code Playgroud)

如果你有URL,你仍然可以使用URLComponents:

let http = URL(string: "http://some.com/example.html")!
var comps = URLComponents(url: http, resolvingAgainstBaseURL: false)!
comps.scheme = "https"
let https = comps.url!
Run Code Online (Sandbox Code Playgroud)

注意:我已经!在几个地方使用过来展示核心解决方案.根据需要为正确的代码提供适当的可选和错误处理.

  • 如果原始 url 是 `x.com`,最终结果将是 `https:x.com`,这不是一个有效的 URL (2认同)