简体   繁体   English

Alamofire请求在连接速度慢时使我的应用程序崩溃

[英]Alamofire request crashes my app on slow connection

I'm facine a problem with my ios APP. 我迷上了ios APP的问题。 I'm using Alamofire to make my http requests to my REST API. 我正在使用Alamofire向REST API发出http请求。

Everything works fine until my app was running on 2G or slow connection. 一切正常,直到我的应用程序在2G或慢速连接上运行。 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. 这是我的API调用示例,我认为我做得正确。

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). Alamofire不会使您的应用程序崩溃,而是通过强制将response.data值不存在(例如超时)解开来使您的应用程序崩溃。 At the simplest level, you need to switch over the response.result value and then handle the success and failure cases. 在最简单的级别上,您需要切换response.result值,然后处理成功和失败的情况。

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. 对于超时或其他系统错误,您将在.failure情况下看到错误。 For other things like response code validation, you may want to add a validate() call before the responseJSON . 对于诸如响应代码验证之类的其他事情,您可能需要在responseJSON之前添加validate()调用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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