swift 具有Argo和自定义错误类型的Generic Alamofire响应序列化程序

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了swift 具有Argo和自定义错误类型的Generic Alamofire响应序列化程序相关的知识,希望对你有一定的参考价值。

static func CloudFlareResponseSerializer<T: Decodable where T == T.DecodedType>() -> GenericResponseSerializer<T> {
    return GenericResponseSerializer { (request, response, data) -> Result<T> in
        guard let validData = data else {
            let failureReason = "Tried to decode response with nil data."
            let error = Error.errorWithCode(.DataSerializationFailed, failureReason: failureReason)
            return .Failure(data, CloudFlareError.SerializationError(error: error))
        }
        
        let JSONSerializer = Request.JSONResponseSerializer(options: .AllowFragments)
        let JSONResult = JSONSerializer.serializeResponse(request, response, validData)
        guard case let .Success(responseJSON) = JSONResult else {
            return .Failure(data, CloudFlareError.SerializationError(error: JSONResult.error! as NSError))
        }
        
        let decodedCloudFlareResponse = CloudFlareResponse.decode(JSON.parse(responseJSON))
        guard case let .Success(cloudFlareResponse) = decodedCloudFlareResponse else {
            let errorString: String
            switch decodedCloudFlareResponse {
            case let .TypeMismatch(error):
                errorString = error
            case let .MissingKey(error):
                errorString = error
            default:
                errorString = "Should never see this."
            }
            
            return .Failure(data, CloudFlareError.DecodingError(decodedString: errorString))
        }
        
        if !cloudFlareResponse.success {
            return .Failure(data, CloudFlareError.ResponseError(response: cloudFlareResponse))
        }
        
        let decodedResponseObject = T.decode(cloudFlareResponse.result)
        guard case let .Success(responseObject) = decodedResponseObject else {
            let errorString: String
            switch decodedResponseObject {
            case let .TypeMismatch(error):
                errorString = error
            case let .MissingKey(error):
                errorString = error
            default:
                errorString = "Should never see this."
            }
            
            return .Failure(data, CloudFlareError.DecodingError(decodedString: errorString))
        }
        
        return .Success(responseObject)
    }
}

以上是关于swift 具有Argo和自定义错误类型的Generic Alamofire响应序列化程序的主要内容,如果未能解决你的问题,请参考以下文章

Argo 错误:对成员“咖喱”的含糊提及

具有自定义文章类型和自定义分类的WordPress库页面

Swift、iboutlet 和自定义控件

Swift中自定义对象和自定义对象数组的通用属性[重复]

Swift:在 tableView Cell 中设置标签和自定义参数

核心数据和自定义属性类型