简体   繁体   中英

Alamofire request crashes my app on slow connection

I'm facine a problem with my ios APP. I'm using Alamofire to make my http requests to my REST API.

Everything works fine until my app was running on 2G or slow connection. It crashes the app without any error message on my debugger.

Here is a example of my API call, I think I'm doing it the right way.

Do you know what I can do to handle slow connections ?

Thank you for your reply

AF.request(url_to_call, method: .patch, headers: headers).responseJSON{response in
    let error_code = response.response?.allHeaderFields["Nx-Error-Code"] ?? "200"

    if (error_code as! String != "200"){
        parseErrorCode(code: error_code as! String)
    } else {
        do{
            let json = try JSON(data: response.data!)
            print(json)
        } catch {
            print(error)
        }
    }
}

Alamofire isn't crashing your app, you are crashing your app by force unwrapping the response.data value when it may not exist (like a timeout). At the simplest level, you need to switch over the response.result value and then handle the success and failure cases.

AF.request(url_to_call, method: .patch, headers: headers).responseJSON { response in
    switch response.result {
    case let .success(value): // Handle success.
    case let .failure(error): // Handle failure.
    }
}

For timeouts, or other system errors, you'll see the error in the .failure case. For other things like response code validation, you may want to add a validate() call before the responseJSON .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM