Skip to content

Instantly share code, notes, and snippets.

@jshier
Last active February 12, 2017 23:06
Show Gist options
  • Save jshier/f08f08e05d994b5bdc7d to your computer and use it in GitHub Desktop.
Save jshier/f08f08e05d994b5bdc7d to your computer and use it in GitHub Desktop.
Custom ResponseSerializer for Alamofire 3
static func CloudFlareResponseSerializer<T: Decodable where T == T.DecodedType>() -> ResponseSerializer<T, CloudFlareError> {
return ResponseSerializer { (request, response, data, error) in
guard error == nil else {
return .Failure(CloudFlareError.NetworkError(error: error!))
}
let JSONResult = Request.JSONResponseSerializer().serializeResponse(request, response, data, nil)
guard case let .Success(responseJSON) = JSONResult else {
return .Failure(CloudFlareError.SerializationError(error: JSONResult.error!))
}
let decodedCloudFlareResponse = CloudFlareResponse.decode(JSON(responseJSON))
guard case let .Success(cloudFlareResponse) = decodedCloudFlareResponse else {
return .Failure(CloudFlareError.DecodingError(decodedString: decodedCloudFlareResponse.error!.description))
}
guard cloudFlareResponse.success else {
return .Failure(CloudFlareError.ResponseError(response: cloudFlareResponse))
}
let decodedResponseObject = T.decode(cloudFlareResponse.result)
guard case let .Success(responseObject) = decodedResponseObject else {
return .Failure(CloudFlareError.DecodingError(decodedString: decodedResponseObject.error!.description))
}
return .Success(responseObject)
}
}
@grantkemp
Copy link

I have been struggling to understand this approach. All the other custom serializers seem to extend AFNetworking.request whereas this is a static func. Can you provide some more guidance how I can add in those custom codes for common things like 404 errors?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment