Last active
February 12, 2017 23:06
-
-
Save jshier/f08f08e05d994b5bdc7d to your computer and use it in GitHub Desktop.
Custom ResponseSerializer for Alamofire 3
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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?