I try to make custom response serialization with Alamofire
I follow what written in README and create protocol and extension
@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)
})
}
}
but when I try to conform it I got this error Type 'my_model_class' does not conform to protocol 'ResponseObjectSerializable'
My model is just a bare-bone class
final class Shot: ResponseObjectSerializable {
required init?(response: NSHTTPURLResponse, representation: AnyObject) {
}
}
Use this with Xcode 6.3, anyone experienced this? and know how to make this work?
Response
to @airspeed The error go away, but what confusing me is in Apple Swift document they have an example on @objc protocol and the swift class that conform it doesn't need @objc
@objc protocol CounterDataSource {
optional func incrementForCount(count: Int) -> Int
optional var fixedIncrement: Int { get }
}
class TowardsZeroSource: CounterDataSource {
func incrementForCount(count: Int) -> Int {
if count == 0 {
return 0
} else if count < 0 {
return 1
} else {
return -1
}
}
}
Shot isn’t marked as @objc, unlike the protocol, so your init doesn’t match the requirement:
@objc public protocol ResponseObjectSerializable {
init?(response: NSHTTPURLResponse, representation: AnyObject)
}
final class Shot: ResponseObjectSerializable {
@objc required init?(response: NSHTTPURLResponse, representation: AnyObject) {
}
}
results in the error:
note: protocol requires initializer
init(response:representation:)with type(response: NSHTTPURLResponse, representation: AnyObject)init?(response: NSHTTPURLResponse, representation: AnyObject)` ^note: candidate is not
@objc, but protocol requires it
Stick an @objc in front of the definition of Shot and it should compile.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With