簡體   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