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

时间:2018-07-09 14:55:15

标签: ios swift nsurlsession completionhandler urlsession

我正在从带有完成处理程序的单独类中发出请求,一旦我从另一个类中调用该方法来调用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)

    }
}

请帮助。

1 个答案:

答案 0 :(得分: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

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

 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 

         }
         //...}
 }