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

Posted

技术标签:

【中文标题】在完成处理程序中隐藏http状态代码的进度条 - Swift 4【英文标题】:Hiding progress bar upon http status code inside completion handler - Swift 4 【发布时间】:2018-07-09 14:55:14 【问题描述】:

我正在使用完成处理程序从一个单独的类发出请求,一旦我调用从另一个类调用 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 作为参数传递给 completionHandler。现在,您有一个成功参数和一个错误参数。如果要将 statusCode 添加为 Int,则可以从您指定的第二种方法访问 statusCode。 【参考方案1】:

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

 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

通过completionBlock 返回不希望出现statusCode 的错误情况。

 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 

         
         //...
 

【讨论】:

我会检查并更新你。感谢您的时间伙伴。

以上是关于在完成处理程序中隐藏http状态代码的进度条 - Swift 4的主要内容,如果未能解决你的问题,请参考以下文章

C# WinForm自定义进度条

用于多处理的 tkinter 进度条

Ajax+PHP打造等待进度条效果

状态条进度条

使用 Spring 框架的作业状态进度条

QML 进度条不动