RxSwift自定义API包装器

时间:2016-10-24 13:34:14

标签: ios swift rx-swift

我试图用RxSwift包装我的API调用。我没有使用任何第三方库进行这些调用。我面临的问题是自定义错误对象。所有API调用都返回标准的JSON错误对象。这是一个例子:

{
  "error": {
     "code": 11001,
     "message": "Bad request",
     "errors": [
            "The accesstoken field is required."
            ]
  }
}

这是发送API请求的代码

func CallAPI(withParameters parameters: [String : AnyObject]?,
             queryToSearchFor query: String?) -> Observable<AnyObject?>? {

    return Observable.create({ (observable) -> Disposable in
        ServerInterface.getRequest(
            withBaseURl: nil,
            withFunctionName: "util/load_companies/" + (query ?? ""),
            havingFunctionsParameters: nil,
            andHeaderParameters: parameters,
            withCompletionHandler: { (response) in
                guard response.responseCode == kSuccessCode else {
                    observable.on(.error( response.responseError  as! Error))
                    return
                }

                observable.on(.next(response.responseData))
                observable.on(.completed)
        })
        return Disposables.create {
            print("Request Cancelled")
        }
    })

}

ServerInterface.getRequest()有一个ServerInterfaceResponse类型的完成处理程序,其中包含ServerInterfaceError。当API返回错误时,我希望ObserverOn这个对象 问题出现在这一行

observable.on(.error( response.responseError as! Error))

在运行时,它崩溃并出现错误

  

&#39;无法转换ServerInterfaceError类型的值&#39;到&#39;错误&#39;

这是我的自定义错误对象

class ServerInterfaceError: NSObject, Error {
    var errorCode: Int?
    var errorMessage: String?
    var errorDebugger: [String]?

    func error(_ code: Int?, message: String?,
               debugger: [String]?) -> ServerInterfaceError {

        let serverError = ServerInterfaceError.init()
        serverError.errorCode = code
        serverError.errorMessage = message
        serverError.errorDebugger = debugger

        return serverError

    }
}

这是我的自定义APIResponse对象。它包含ServerInterfaceError类型的属性responseError

class ServerInterfaceResponse: NSObject {
    var responseCode: Int?
    var responseData: AnyObject?
    var responseMessage: String?
    var responseError: ServerInterfaceError?

    func response(_ code: Int?, data: AnyObject?, message: String?, error: ServerInterfaceError?) -> ServerInterfaceResponse {
         let serverResponse = ServerInterfaceResponse.init()
         serverResponse.responseCode = code
         serverResponse.responseData = data
         serverResponse.responseMessage = message
         serverResponse.responseError = error

        return serverResponse
    }

    override var description: String {
      return "Response Code = \(responseCode) | Response Data = \(responseData) | Response Message = \(responseMessage) | Response Error = {\(responseError)}"
    }
}

如何将自定义对象发送到observable.on(.error( ))

0 个答案:

没有答案