Moya 解决地址中带有 ? 问题 记录

问题:当你的请求地址中包含?,被系统自动转化%3F,导致请求失败。

因为源码中的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
        if target.path.isEmpty {
            self = target.baseURL
        } else {
            self = target.baseURL.appendingPathComponent(target.path)
        }
    }

当你的请求中包含?号,会走else,于是就被自动转化成为了%3F,这个就很难受了,直接就404,去Git 上面搜索一下这个问题,发现遇到的还真不少,上面也不乏有些解决方案,这里也是参考了上面提出的一些解决方案,然后自己写了一个方法去解决这个问题(只是对原来的代码进行了扩展,不会对源码进行污染)。

  • 1、新建一个文件: URL.swift
  • 2、导入框架 import Moya
  • 3、自己写一个初始化的方法
init<T: TargetType>(t target: T) {
       if target.path.isEmpty {
           self = target.baseURL
       } else if target.path.contains("?") {
           // 这里直接强制解包了,这里可以修改,如果你需要。
           self = URL.init(string: target.baseURL.absoluteString + target.path)!
       } else {
           self = target.baseURL.appendingPathComponent(target.path)
       }
   }
  • 4、在把Endpoint的初始化中调用我们这个方法
public extension MoyaProvider {
   public final class func pqEndpointMapping(for target: Target) -> Endpoint {
       return Endpoint(
           url: URL(t: target).absoluteString,
           sampleResponseClosure: { .networkResponse(200, target.sampleData) },
           method: target.method,
           task: target.task,
           httpHeaderFields: target.headers
       )
   }
}

最后在初始化Moya的时候把自带的enpointClosure替换我们自己写的,就可以了let Provider = MoyaProvider<UserAPI>(endpointClosure: MoyaProvider.pqEndpointMapping)

猜你喜欢

转载自blog.csdn.net/weixin_34161032/article/details/86902926