Done Done - 3 months ago 24
iOS Question

Error Handling with Alamofire in Swift 2

Hi I am practising some code, my code is fine with

case .Success(let value):
and it is displaying alert but will
case .Failure(let error):
display alert with The 4xx class of status code?

Alamofire.request(.GET, URL).responseJSON { (response) -> Void in
if let value = response.result.value {

let json = JSON(value)

switch response.result {
case .Success(let value):

let name = json["name"].string
if let nothing = name {
self.alertMessage(message: "Name not Found")
} else {
self.alertMessage(message: "Name Found")
}
case .Failure(let error):
self.alertMessage(message: "Error 4xx / 5xx")
}

Rob Rob
Answer

You can use validate to check status codes:

Alamofire.request(.GET, URL)
    .validate()    // or, if you just want to check status codes, validate(statusCode: 200..<300)
    .responseJSON { response in
        switch response.result {
        case .Success(let value):
            let json = JSON(value)

            if let name = json["name"].string {
                self.alertMessage(message: "Name Found: \(name)")
            } else {
                self.alertMessage(message: "Name not Found")
            }
        case .Failure(let error):
            self.alertMessage(message: "Error 4xx / 5xx: \(error)")
        }
}

Or, in Swift 3:

Alamofire.request(url)
    .validate()    // or, if you just want to check status codes, validate(statusCode: 200..<300)
    .responseJSON { response in
        switch response.result {
        case .success(let value):
            let json = JSON(value)

            if let name = json["name"].string {
                self.alertMessage(message: "Name Found: \(name)")
            } else {
                self.alertMessage(message: "Name not Found")
            }
        case .failure(let error):
            self.alertMessage(message: "Error 4xx / 5xx: \(error)")
        }
}

Also note that you should probably move the examination of response.result.value to inside the Success section (or just grab the value passed there). Also, the determination of whether name is found was backwards.