user2636197 user2636197 - 10 days ago 6
iOS Question

Swift alamofire refactoring trying to return status code

I have began to refactor my Alamofire api calls to keep them in a seperate file. The only problem is that I dont know how to return the statuscode as well.

Api file:

static func getCategories(_ catId: Int, response: @escaping (JSON) -> ()) {
let urlString = baseURL + ResourcePath.categories(catId: catId).description
Alamofire.request(urlString, encoding: JSONEncoding.default, headers: headers).responseJSON{ (responseData) -> Void in

let cCatData = JSON(responseData.result.value ?? [])
response(cCatData)

}
}


Then in my VC:

Api.getCategories(catId) { (JSON) -> () in
self.categories = JSON["catData"]
self.tableView.reloadData()
}


But I need to know if the status code is 200/400/404/422/500 and I dont want to use the .validate() function, I want to pass the status code

Normally if I would have everything in the same file I would get the status code by:

Alamofire.request("https://www.something", parameters: parameters, encoding: JSONEncoding.default, headers: headers)
.responseJSON() { response in
if let statusCode = response.response?.statusCode {

if statusCode == 200 {

}

}

Rob Rob
Answer

If you want your closure to pass back the status code, then add an Int? parameter and pass it back:

static func getCategories(_ catId: Int, response: @escaping (JSON, Int?) -> ()) {
    let urlString = baseURL + ResourcePath.categories(catId: catId).description
    Alamofire.request(urlString, encoding: JSONEncoding.default, headers: headers).responseJSON { responseData in
        let cCatData = JSON(responseData.result.value ?? [])
        response(cCatData, responseData.response?.statusCode)
    }
}

Or I might use more standard variable/parameter names:

static func getCategories(_ catId: Int, completionHandler: @escaping (JSON, Int?) -> ()) {
    let urlString = baseURL + ResourcePath.categories(catId: catId).description
    Alamofire.request(urlString, encoding: JSONEncoding.default, headers: headers).responseJSON { response in
        let cCatData = JSON(response.result.value ?? [])
        completionHandler(cCatData, response.response?.statusCode)
    }
}

Either way, you can then do:

Api.getCategories(catId) { json, statusCode in 
    guard statusCode == 200 else {
        print("status code not 200! \(statusCode)")
        return
    }

    // if you got here, the status code must have been 200
}