使用Moya将参数附加到每个网络呼叫

时间:2018-11-09 13:03:19

标签: swift alamofire rx-swift moya

如何通过(Rx)Moya将默认请求参数(例如AppID)附加到每个API调用中?

2 个答案:

答案 0 :(得分:0)

Moya中的

Endpoint类具有adding(newHTTPHeaderFields:),该字典带有一个字典,您可以在此处提供将为每个请求发送的其他http标头。文档link

let endpointClosure = { (target: TargetType) -> Endpoint in
    let defaultEndpoint = MoyaProvider.defaultEndpointMapping(for: target)
    return defaultEndpoint.adding(newHTTPHeaderFields: ["AppID": "MY_APP_ID"])
}
let provider = MoyaProvider<TargetType>(endpointClosure: endpointClosure)

答案 1 :(得分:0)

    //Create a BaseMoyaProvider class and add default paramaters 

    import Moya
    import Result
    import SwiftyJSON

    class BaseMoyaProvider {
      static func create<T: TargetType>(service: T.Type) -> (T)->(Endpoint) {
        let closure = { (target: T) -> Endpoint in
          let endpoint = MoyaProvider.defaultEndpointMapping(for: target)

          switch endpoint.task {
          case .requestParameters(
            let _parameters,
            let _encoding):

            let parameters = _parameters
              .appending([
                "AppID" : "XXXXXXXXXXX"
                ])

            let task = Task.requestParameters(
              parameters: parameters,
              encoding: _encoding
            )

            return endpoint
              .replacing(task: task)
          default: return endpoint
          }`enter code here`
        }
        return closure
      }
    } 

//Extend MoyaProvider class

extension MoyaProvider {
  static func build() -> MoyaProvider<Target> {
    let provider = BaseMoyaProvider
      .create(service: Target.self)

    return MoyaProvider<Target>(
      endpointClosure: provider,
      plugins: [ ApiLogger() ]
    )
  }

  // MARK: Request
  func rx_request<T: Mappable>(_ target: Target) -> Observable<T> {
    return Observable.create({ (observer) -> Disposable in
      let request = self.request(target, completion: { (result) in
        //Handle response
      })
      return Disposables.create {
        request.cancel()
      }
    })
  }
}