Swift URL" ? 转义后%3F "

今天搞一个老项目,使用的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
        }
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • .bat脚本基本命令语法 目录 批处理的常见命令(未列举的命令还比较多,请查阅帮助信息) 1、REM 和 :: 2...
    庆庆庆庆庆阅读 8,245评论 1 19
  • JAVA数据处理 字符串处理 一般程序需要处理大量文本数据,Java 语言的文本数据被保存为字符或字符串类型。字符...
    夜雨流云阅读 1,180评论 0 0
  • 久违的晴天,家长会。 家长大会开好到教室时,离放学已经没多少时间了。班主任说已经安排了三个家长分享经验。 放学铃声...
    飘雪儿5阅读 7,587评论 16 22
  • 创业是很多人的梦想,多少人为了理想和不甘选择了创业来实现自我价值,我就是其中一个。 创业后,我由女人变成了超人,什...
    亦宝宝阅读 1,889评论 4 1
  • 今天感恩节哎,感谢一直在我身边的亲朋好友。感恩相遇!感恩不离不弃。 中午开了第一次的党会,身份的转变要...
    迷月闪星情阅读 10,620评论 0 11