I am using the below code to download data from a server. According to Crashlytics, we see a crash occurred (EXC_BREAKPOINT) on the conditional evaluation (the 'if' statement). I suspect it is because the code unpacking the optional member "statusCode" - I am new to Swift (10 years doing Obj-C) - and I am not certain what the best, safest way is to unpack this variable without causing a crash.
Note that this app its using SwiftyJSON, though I do not think that is relevant.
Alamofire.request(url).responseJSON { (response) in if (response.response?.statusCode)! >= 200 && (response.response?.statusCode)! < 300
Alamofire.request(url).validate().responseJSON { response in
switch response.result {
case .success(let json):
// do something with json
case .failure(let error):
// handle error
}
}
The validate()
method replaces your line checking the statusCode
. It defaults to using acceptableStatusCodes
which are 200..<300
.
I think that's the best way to handle this specific case.
For more general cases, you should avoid force unwrapping. Unwrap the optional using guard
or if let
. The Swift docs explain that in detail.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments