嗨,我正在练习一些代码,我的代码很好用case .Success(let value):它显示警告但会出现故障.故障(让错误):用4xx类状态代码显示警告?
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")
}
最佳答案 您可以使用验证来检查状态代码:
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)")
}
}
或者,在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)")
}
}
另请注意,您应该将response.result.value的检查移到Success部分内部(或者只是获取传递的值).此外,确定是否找到名称是向后的.