📜  urlencode string swift (1)

📅  最后修改于: 2023-12-03 14:48:14.368000             🧑  作者: Mango

使用 Swift 进行 URL 编码字符串

当在处理网页 URL 或是 API 调用时,我们常常需要将字符串进行 URL 编码以便于传输。本文将介绍如何在 Swift 中进行 URL 编码的操作。

使用 addingPercentEncoding(withAllowedCharacters:) 函数

在 Swift 中,可以使用 addingPercentEncoding(withAllowedCharacters:) 函数进行 URL 编码的操作。这个函数接受一个 CharacterSet 类型的参数,表示可以进行编码的字符集。

let originalString = "http://example.com/path with spaces"
let encodedString = originalString.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)

print(encodedString) // "http://example.com/path%20with%20spaces"

上面的代码中,urlHostAllowed 表示对 URL 中需要进行编码处理的字符集,这里我们选择将空格进行编码为 %20

如果我们想要对更多类型的字符进行编码处理,可以使用另外一个预定义的字符集 urlQueryAllowed

let charactersToEncode = CharacterSet(charactersIn: "!*'();:@&=+$,/?%#[]")

let originalString = "http://example.com/path?name=苹果&price=¥8.99"
let encodedString = originalString.addingPercentEncoding(withAllowedCharacters: charactersToEncode)

print(encodedString) // "http://example.com/path?name=%E8%8B%B9%E6%9E%9C&price=%C2%A58.99"

上面的代码中,我们自定义了需要进行编码处理的字符集 charactersToEncode,并将 URL 中的中文和货币符号进行了编码,结果展示了编码后的 URL。

使用 URLComponents 类型进行 URL 编码

除了上面提到的 addingPercentEncoding(withAllowedCharacters:) 函数,Swift 还提供了一种更直接的方式对 URL 进行编码处理,那就是使用 URLComponents 类型:

let originalString = "http://example.com/path?name=苹果&price=¥8.99"

if var components = URLComponents(string: originalString) {
    components.queryItems = components.queryItems?.map { item in
        guard let value = item.value else { return item }
        return URLQueryItem(name: item.name, value: value.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed))
    }
    print(components.string)
}

上面的代码中,我们使用 URLComponents 将原始字符串解析为 URLComponents 对象,然后对其中的 queryItems 进行了遍历,并使用 addingPercentEncoding(withAllowedCharacters:) 函数对其进行 URL 编码处理。

结论

在 Swift 中进行 URL 编码处理的操作十分简单。上述两种方式都能够对 URL 字符串进行有效的编码处理,开发者可以根据实际需要选择更加适合自己的方式进行处理操作。