问题描述
我正在使用 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 是一个字符串状态变量。
我意识到我可以做一些类似 self.error = "There was an error" 的事情,但我想向用户提供一些关于错误实际是什么的反馈,但我似乎找不到正确的属性(即类似 err.stringValue、err.description 等)来执行此操作。似乎这里有一些源代码 https://github.com/Alamofire/Alamofire/blob/master/Source/AFError.swift,但我不确定这与我想要获取的字符串值有什么关系。
这里的任何帮助将不胜感激。
解决方法
可以试试Fooish
,也可以在函数完成时得到错误并返回err.localizedDescription
对于这种情况,您始终可以使用字符串插值,例如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)")