今天搞一个老项目,使用的Moya+RXSwift,在做网络请求时,需要参数拼接到接后面,如下例子
let url = URL(string: "https://example.com")
let path = "/otherPath?name=wangDemo&age=18"
let urlWithPath = url?.appendingPathComponent(path)
print(urlWithPath)
// 输出:https://example.com/otherPath%3Fname=wangDemo&age=18
这样会报什么错?想知道的可以跑一下代码。
这个涉及URL编码url-encoding
,会把特殊符号给转义,?
转义后即是%3F
,我们正常请求一般不会有问题,但是用appendingPathComponent
就会有转义的问题,说到这大家应该知道怎么解决了吧。
import Foundation
public extension URL {
/// Initialize URL from Moya's `TargetType`.
init<T: TargetType>(target: T) {
// When a TargetType's path is empty, URL.appendingPathComponent may introduce trailing /, which may not be wanted in some cases
// See: https://github.com/Moya/Moya/pull/1053
// And: https://github.com/Moya/Moya/issues/1049
let targetPath = target.path
if targetPath.isEmpty {
self = target.baseURL
} else {
// self = target.baseURL.appendingPathComponent(targetPath)
//修改如下,如果有更好的方法,欢迎补充
let urlWithPath = target.baseURL.absoluteString + targetPath
self = URL(string: urlWithPath) ?? target.baseURL
}
}
}