Last active
March 15, 2017 15:02
-
-
Save T-Pham/3df34ab571ac244666f12744a31eda76 to your computer and use it in GitHub Desktop.
Alamofire SwiftyJSON Serializer
This file contains hidden or 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
// | |
// 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