gpt4 book ai didi

ios - 在完成处理程序中的 http 状态代码上隐藏进度条 - Swift 4

转载 作者:行者123 更新时间:2023-11-28 14:31:12 25 4
gpt4 key购买 nike

我正在从一个带有完成处理程序的单独类发出请求,一旦我调用方法从另一个类调用 Web 服务,就会显示进度条,现在如果状态代码不是 200,我需要隐藏进度条。请检查以下代码。

API.swift

func getProgramsFromApi(url : String, authToken: String,
completionBlock : @escaping APICompletionHandlerProgram) -> Void {

var request = URLRequest(url: URL(string: url)!)
request.httpMethod = "GET"
request.setValue("application/json", forHTTPHeaderField: "Accept")
request.setValue(authToken, forHTTPHeaderField: "X-token")
let task = URLSession.shared.dataTask(with: request) { data,
response, error in
guard let data = data, error == nil else {
// check for fundamental networking error
print("error=\(String(describing: error))")
DispatchQueue.main.async {
SCLAlertView().showError("Error", subTitle:
(response?.description)!)
}
return
}


if let httpStatus = response as? HTTPURLResponse,
httpStatus.statusCode != 200 {
//hide progress bar here.
// check for http errors
print("statusCode should be 200, but is \
(httpStatus.statusCode)")
print("response = \(String(describing: response))")

}else{


do {

let jsonResult = try? JSONDecoder().decode(Programs.self,
from: data)

completionBlock(jsonResult!, error)
}catch let jsonError{
print("some error \(jsonError)")
completionBlock(nil!, error)
}

}

}
task.resume()
}

如果状态码不是200,我想在下面的方法中隐藏进度条。

Program.swift

func fetchDataFromProgramsAPI() {

let apiKEY = UserDefaults.standard.string(forKey: "API_TOKEN")

apiService.getProgramsFromApi(url:
Constants.BASE_URL+APIMethod().programs, authToken: apiKEY!){
(success, err) in
Helper.showHUD(hud: self.HUD)
if success.data?.count == 0{
Helper.hideHUD(hud: self.HUD)
return
}


DispatchQueue.main.async {
self.programTable?.reloadData()
}
Helper.hideHUD(hud: self.HUD)

}
}

请帮忙。

最佳答案

如果您只对 statusCode 是否返回 200 感兴趣,一个简单的方法是在您的 error block 中返回它的完成。

 enum NetworkCallError: Error {
case responseUnsuccessful
//I'd even make a case for all anticipated status codes there for I could handle any status and possibly retry the call based on whatever error is returned.
case responseUnsuccessful(code: Int)
}

调整您的 typealias 以包含您的新错误

 typealias APICompletionHandlerProgram = (Data?, NetworkCallError?) -> Void

通过 completionBlockstatusCode 不受欢迎的地方返回错误案例。

 if let httpStatus = response as? HTTPURLResponse, 
httpStatus.statusCode != 200 {
//Hide status bar here < Don't try to manipulate your view from your model.
//Throw your error in the completion block here.
completionBlock(nil, NetworkCallError.responseUnsuccessful)

//You could move this to a localizedDescription variable for `responseUnsuccessful` but that's out of the scope for this answer.
print("statusCode should be 200, but is \
(httpStatus.statusCode)")
print("response = \(String(describing: response))")
}

在调用站点:

在继续之前检查错误。

 func fetchDataFromProgramsAPI() {

//{...

apiService.getProgramsFromApi(url:
Constants.BASE_URL+APIMethod().programs, authToken: apiKEY!){
(success, err) in
Helper.showHUD(hud: self.HUD)
//Don't forget to unwrap the values in the tuple since they may or may not exist.
guard let success = success,
let err = err else { return }
switch err {
//Handle your error by retrying call, presenting an alert, whatever.
case .responseUnsuccessful
Helper.HideHUD(hud: self.HUD)
//{...}
return

}
//...}
}

关于ios - 在完成处理程序中的 http 状态代码上隐藏进度条 - Swift 4,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51248461/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com