【问题标题】:Encode URL in Swift 5在 Swift 5 中编码 URL
【发布时间】:2020-03-23 13:46:05
【问题描述】:

在 Swift 中编码 URL 最简洁的方法是什么?

我有

let request_url = URL(string:"http://api.openweathermap.org/data/2.5/weather?appid=dca0aa44807a0bc05ed51c6a85472341&q="+"New York")

如何通过 swift 中可用的一些简单方法在 New 和 York 之间添加 + 而不是空格?

【问题讨论】:

  • replacingOccurrences(of:with:)?
  • 这能回答你的问题吗? Swift - encode URL
  • 是的。我们可以进行字符串操作。但是我们怎样才能使用某种方法来自动为我们做这件事呢? + 号只是一个例子。我们在 URL 中还有其他内容。我们可以通过一些 URL 构建器来做到这一点吗?
  • @fl034 不,它没有帮助。我需要一个简单的方法,它采用字符串 URL 并将其转换为格式化的 URL(例如添加 + 符号而不是空格)

标签: ios xcode swift5


【解决方案1】:

如果我理解正确,您希望将空格编码为 + 并正确编码其他特殊字符。 因此,这种方法使用本机函数addingPercentEncoding(withAllowedCharacters:) 将空间转换为%20。然后我们将所有出现的%20 替换为+

extension URL {
    init?(encoding string: String) {
        let encodedString = string
            .addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)                
            .replacingOccurrences(of: "%20", with: "+")                
        guard let encodedString != nil else { return nil }
        self.init(string: encodedString!)
    }
}

这被封装在一个URL init 函数中,所以你可以这样使用它:

let requestUrl = URL(encoding: "http://api.openweathermap.org/data/2.5/weather?appid=dca0aa44807a0bc05ed51c6a85472341&q="+"New York")

【讨论】:

    猜你喜欢
    • 2023-03-06
    • 2011-12-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多