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

问题描述 投票:0回答:1

我的ios APP存在问题。我正在使用Alamofire向我的REST API发出我的http请求。

一切正常,直到我的应用程序在2G或慢速连接上运行。它在我的调试器上没有任何错误消息时崩溃了应用程序。

这是我的API调用的一个例子,我想我正在以正确的方式做。

你知道我能做些什么来处理慢速连接吗?

谢谢您的回复

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)
        }
    }
}
ios swift alamofire
1个回答
1
投票

Alamofire没有崩溃你的应用程序,你正在崩溃你的应用程序通过强制解开response.data值可能不存在(如超时)。在最简单的级别,您需要切换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.
    }
}

对于超时或其他系统错误,您将在.failure案例中看到错误。对于响应代码验证等其他内容,您可能需要在validate()之前添加responseJSON调用。

© www.soinside.com 2019 - 2024. All rights reserved.