Created
July 31, 2015 14:25
-
-
Save jk/0a74a7499151081a6c29 to your computer and use it in GitHub Desktop.
Response Object and Collection Serializable
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
@objc public protocol ResponseObjectSerializable { | |
init(response: NSHTTPURLResponse, representation: AnyObject) | |
} | |
extension Alamofire.Request { | |
public func responseObject<T:ResponseObjectSerializable>(completionHandler: (NSURLRequest, NSHTTPURLResponse?, T?, NSError?) -> Void) -> Self { | |
let serializer: Serializer = { | |
(request, response, data) in | |
let JSONSerializer = Request.JSONResponseSerializer(options: .AllowFragments) | |
let (JSON: AnyObject?, serializationError) = JSONSerializer(request, response, data) | |
if response != nil && JSON != nil { | |
return (T(response: response!, representation: JSON!), nil) | |
} else { | |
return (nil, serializationError) | |
} | |
} | |
return response(serializer: serializer, completionHandler: { | |
(request, response, object, error) in | |
completionHandler(request, response, object as? T, error) | |
}) | |
} | |
} | |
@objc public protocol ResponseCollectionSerializable { | |
static func collection(#response: NSHTTPURLResponse, representation: AnyObject) -> [Self] | |
} | |
extension Alamofire.Request { | |
public func responseCollection<T: ResponseCollectionSerializable>(completionHandler: (NSURLRequest, NSHTTPURLResponse?, [T]?, NSError?) -> Void) -> Self { | |
let serializer: Serializer = { (request, response, data) in | |
let JSONSerializer = Request.JSONResponseSerializer(options: .AllowFragments) | |
let (JSON: AnyObject?, serializationError) = JSONSerializer(request, response, data) | |
if response != nil && JSON != nil { | |
return (T.collection(response: response!, representation: JSON!), nil) | |
} else { | |
return (nil, serializationError) | |
} | |
} | |
return response(serializer: serializer, completionHandler: { (request, response, object, error) in | |
completionHandler(request, response, object as? [T], error) | |
}) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment