Skip to content

Instantly share code, notes, and snippets.

@T-Pham
Last active March 15, 2017 15:02
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save T-Pham/3df34ab571ac244666f12744a31eda76 to your computer and use it in GitHub Desktop.
Save T-Pham/3df34ab571ac244666f12744a31eda76 to your computer and use it in GitHub Desktop.
Alamofire SwiftyJSON Serializer
//
// AlamofireSwiftyJSONSerializer.swift
//
// Created by Thanh Pham on 7/21/16.
//
import Alamofire
import SwiftyJSON
extension Request {
internal static func newError(code: Error.Code, failureReason: String) -> NSError {
let errorDomain = "com.alamofireswiftyjson.error"
let userInfo = [NSLocalizedFailureReasonErrorKey: failureReason]
let returnError = NSError(domain: errorDomain, code: code.rawValue, userInfo: userInfo)
return returnError
}
public func responseSwiftyJSON(queue queue: dispatch_queue_t? = nil, keyPath: String? = nil, completionHandler: Response<JSON, NSError> -> Void) -> Self {
return response(queue: queue, responseSerializer: Request.SwiftyJSONSerializer(), completionHandler: completionHandler)
}
public static func SwiftyJSONSerializer() -> ResponseSerializer<JSON, NSError> {
return ResponseSerializer { request, response, data, error in
guard error == nil else {
return .Failure(error!)
}
guard let data = data else {
let failureReason = "Data could not be serialized. Input data was nil."
let error = newError(.DataSerializationFailed, failureReason: failureReason)
return .Failure(error)
}
var dataError: NSError?
let json = JSON(data: data, error: &dataError)
guard dataError == nil else {
return .Failure(dataError!)
}
return .Success(json)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment