Skip to content

Instantly share code, notes, and snippets.

@grantkemp
Created February 12, 2017 23:36
Show Gist options
  • Save grantkemp/bb00419f8a84c2698d56fcf64b127ba0 to your computer and use it in GitHub Desktop.
Save grantkemp/bb00419f8a84c2698d56fcf64b127ba0 to your computer and use it in GitHub Desktop.
Adding support for common error status codes like 404, 403 to the responseJson serializer in Alamofire.
// Adding support for common error status codes like 404, 403 to the responseJson serializer in Alamofire.
//
// AlamofireAuto.swift
// Speedy
//
// Created by Grant Kemp on 12/02/2017.
// Copyright © 2017 Grant Kemp. All rights reserved.
//
import Foundation
import Alamofire
extension Alamofire.Request {
enum BackendError: Error {
case network(error: Error) // Capture any underlying Error from the URLSession API
case dataSerialization(error: Error)
case jsonSerialization(error: Error)
case xmlSerialization(error: Error)
case objectSerialization(reason: String)
}
public static func serializeResponseJSONSimple(
options: JSONSerialization.ReadingOptions,
response: HTTPURLResponse?,
data: Data?,
error: Error?)
-> Result<Any>
{
guard error == nil else {
//error!.localizedDescription is the only property
return .failure(error!) }
if let response = response{ return .success(NSNull()) }
guard let validData = data, validData.count > 0 else {
return .failure(AFError.responseSerializationFailed(reason: .inputDataNilOrZeroLength))
}
do {
let json = try JSONSerialization.jsonObject(with: validData, options: options)
return .success(json)
} catch {
return .failure(AFError.responseSerializationFailed(reason: .jsonSerializationFailed(error: error)))
}
}
}
extension DataRequest {
public static func jsonResponseSerializer(
options: JSONSerialization.ReadingOptions = .allowFragments)
-> DataResponseSerializer<Any>
{
return DataResponseSerializer { _, response, data, error in
return Request.serializeResponseJSON(options: options, response: response, data: data, error: error)
}
}
@discardableResult
public func responseSimpleJSON(
queue: DispatchQueue? = nil,
options: JSONSerialization.ReadingOptions = .allowFragments,
completionHandler: @escaping (DataResponse<Any>) -> Void)
-> Self
{
return response(
queue: queue,
responseSerializer: DataRequest.jsonResponseSerializer(options: options),
completionHandler: completionHandler
)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment