0

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

    }
}

请帮忙。

4

1 回答 1

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 

         }
         //...}
 }
于 2018-07-09T19:12:29.673 回答