Last active
August 29, 2015 14:23
-
-
Save jqsilver/82a515bfaca9a8552ad0 to your computer and use it in GitHub Desktop.
Alamofire serializer for non-classes
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
typealias JSONDict = [String: AnyObject] | |
// wrapping structs | |
private class Box<T> { | |
let contents: T | |
init(contents: T) { | |
self.contents = contents | |
} | |
} | |
extension Alamofire.Request { | |
private func makeBoxSerializer<ModelType>(modelizer: (JSONDict) -> (ModelType?, NSError?)) -> | |
(NSURLRequest, NSHTTPURLResponse?, NSData?) -> (Box<ModelType>?, NSError?) | |
{ | |
return { (req, res, data) in | |
let jsonSerializer = Alamofire.Request.JSONResponseSerializer() | |
let (data: AnyObject?, error) = jsonSerializer(req, res, data) | |
if let error = error { | |
return (nil, error) | |
} else if let data = data as? JSONDict { | |
// For simplicity, only considering dictionary case for json object | |
let (model, modelError) = modelizer(data) | |
return self.wrapModel(model, error: modelError) | |
} else { | |
return (nil, nil) | |
} | |
} | |
} | |
private func wrapModel<ModelType>(model: ModelType?, error: NSError?) -> (Box<ModelType>?, NSError?) { | |
if let error = error { | |
return (nil, error) | |
} else if let model = model { | |
return (Box(contents: model), nil) | |
} else { | |
return (nil, nil) | |
} | |
} | |
func responseModelStruct<ModelType>( | |
modelizer: (JSONDict) -> (ModelType?, NSError?), | |
completion: (NSURLRequest, NSHTTPURLResponse?, ModelType?, NSError?) -> Void | |
) -> Self | |
{ | |
let boxSerializer = makeBoxSerializer(modelizer) | |
let unboxCompletion: (NSURLRequest, NSHTTPURLResponse?, Box<ModelType>?, NSError?) -> Void = { req, res, box, err in | |
completion(req, res, box?.contents, err) | |
} | |
return responseModelCommon(boxSerializer, completionHandler: unboxCompletion) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment