Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom, content based validator for Alamofire (in Swift)

I know you can add a status code and content type validators, but I'd really love to be able to write my own validator based on the result content - basically I want to make sure the json I'm getting back contains some fields, and that their value is valid.

The way the app I'm working on is currently designed is there's a Server class that handles all the api calls, and the response object is returned to whoever called it, so they can do their logic / update ui, etc.

Now I have a status code validator on all the requests, so I don't need to have it on all external, but I have several apis, that require that custom validation logic, which means I have to add it in all the places that call it, AND that I can't use this amazing syntax:

switch resp.result {
    case .Success(let value):
        print("yay")
    case .Failure:
        print("nay")
}

I'd love any answer/pointer that can help me find a solution,
Thank you all so much in advance! :)

like image 391
Alex Zak Avatar asked Dec 05 '25 05:12

Alex Zak


1 Answers

I wound up having this exact same question and found out what you want to do is write your own response serializer and stop using .validate().

The serializer I'm using is very, very close to the out-of-the-box JSONResponseSerializer, except I make a check for an error.

The only change I make to the stock serializer is within the do-catch statement:

do {
    let JSON = try NSJSONSerialization.JSONObjectWithData(validData, options: options)
    if let responseDict = JSON as? NSDictionary, apiError = NSError.APIErrorFromResponse(responseDict) {
        return .Failure(apiError)
    }
    return .Success(JSON)
} catch {
    return .Failure(error as NSError)
}

APIErrorFromResponse is simply an extension method on NSError that checks the JSON for an error dictionary and populates a custom NSError out of that.

Hopefully this points you in the right direction if you haven't already found a solution!

like image 160
Stakenborg Avatar answered Dec 07 '25 20:12

Stakenborg