繁体   English   中英

获取 Alamofire AFError 错误 Swift 的字符串值

[英]Get string value of Alamofire AFError error Swift

我正在使用 AlamoFire 向我的服务器发出请求,并且我有一个类似这样的设置,其中“self.error”是一个字符串变量。

                    session.request("https://localhost:3000/my-route", method: .post, parameters: parameters, encoding: JSONEncoding.default).responseJSON { response in
                        switch response.result {
                        case .success(let result):
                              print("nice", result)                         
                            
                        case .failure(let err):
                            self.error = err //self.error is a String state variable
                            print("failure")
                        }
                       }

但是,我收到(明智的)错误“无法将类型 'AFError' 的值分配给类型 'String'”,因为我正在尝试设置self.error = err ,并且err是 AFError 类型,而 self.error 是一个字符串 state 变量。

我意识到我可以做一些类似 self.error = "There was an error",但我想向用户提供一些关于错误实际是什么的反馈,我似乎找不到正确的属性(例如 err.stringValue、err.description 等)这样做。 似乎这里有一些源代码https://github.com/Alamofire/Alamofire/blob/master/Source/AFError.swift但我不确定这与我想获得的字符串值有什么关系。

在这里的任何帮助将不胜感激。

您可以尝试err.localizedDescription或者您可以在 function 完成时收到错误并返回completion(error)

对于这种情况,您始终可以使用字符串插值,例如self.error = "\(err)" ,但这不是一个好主意,因为 err 不仅仅是一个字符串,并且可能包含以下内容:

sessionTaskFailed(error: Error Domain=NSURLErrorDomain Code=-1004 "Could not connect to the server." UserInfo={_kCFStreamErrorCodeKey=61, NSUnderlyingError=0x280e37750 {Error Domain=kCFErrorDomainCFNetwork Code=-1004 "(null)" UserInfo={_kCFStreamErrorCodeKey=61, _kCFStreamErrorDomainKey=1}}, _NSURLErrorFailingURLSessionTaskErrorKey=LocalDataTask <78576E38-D021-4ADC-87D4-1C9D81FF0E3A>.<1>, _NSURLErrorRelatedURLSessionTaskErrorKey=( "LocalDataTask <78576E38-D021-4ADC-87D4-1C9D81FF0E3A>.<1>" ), NSLocalizedDescription=Could not connect to the server., NSErrorFailingURLStringKey=https://localhost:3000/my-route, NSErrorFailingURLKey=https://localhost:3000/my-route, _kCFStreamErrorDomainKey=1})

就像@Menaim 已经提到的那样,您可以使用err.localizedDescription ,然后您会得到类似URLSessionTask failed with error: Could not connect to the server.

通常,我不会将错误直接传递给用户。 这取决于您的用户,但他们真的应该知道URLSessionTask是什么吗?

在我看来,您应该为用户定义错误字符串,每个用户都可以理解,并且您应该将err.localizedDescription到控制台,这样您就可以知道发生了什么。

如果您的应用支持多种语言,您可以定义 localizable.strings 文件并翻译错误。

如果这样做print("failure") ,每次出现错误,如何区分错误?

我的建议是这样的:

                case .failure(let err):
                    self.error = "There was an error connecting to the server"
                    print("Failed to connect to backend: \(err.localizedDescription)")

暂无
暂无

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

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