【问题标题】:Swift alamofire refactoring trying to return status codeSwift alamofire 重构试图返回状态码
【发布时间】:2016-11-27 00:44:29
【问题描述】:

我已经开始重构我的 Alamofire api 调用,将它们保存在一个单独的文件中。唯一的问题是我也不知道如何返回状态码。

API 文件:

static func getCategories(_ catId: Int, response: @escaping (JSON) -> ()) {
        let urlString = baseURL + ResourcePath.categories(catId: catId).description
        Alamofire.request(urlString, encoding: JSONEncoding.default, headers: headers).responseJSON{ (responseData) -> Void in

            let cCatData = JSON(responseData.result.value ?? [])
            response(cCatData)

        }
    }

然后在我的 VC 中:

Api.getCategories(catId) { (JSON) -> () in
            self.categories = JSON["catData"]
            self.tableView.reloadData()
        }

但我需要知道状态码是否为 200/400/404/422/500 并且我不想使用 .validate() 函数,我想传递状态码

通常,如果我将所有内容都放在同一个文件中,我会通过以下方式获取状态代码:

Alamofire.request("https://www.something", parameters: parameters, encoding: JSONEncoding.default, headers: headers)
                        .responseJSON() { response in
                            if let statusCode = response.response?.statusCode { 

if statusCode == 200  {

}

}

【问题讨论】:

    标签: ios swift xcode


    【解决方案1】:

    如果你想让你的闭包回传状态码,那么添加一个Int?参数并传回:

    static func getCategories(_ catId: Int, response: @escaping (JSON, Int?) -> ()) {
        let urlString = baseURL + ResourcePath.categories(catId: catId).description
        Alamofire.request(urlString, encoding: JSONEncoding.default, headers: headers).responseJSON { responseData in
            let cCatData = JSON(responseData.result.value ?? [])
            response(cCatData, responseData.response?.statusCode)
        }
    }
    

    或者我可能会使用更标准的变量/参数名称:

    static func getCategories(_ catId: Int, completionHandler: @escaping (JSON, Int?) -> ()) {
        let urlString = baseURL + ResourcePath.categories(catId: catId).description
        Alamofire.request(urlString, encoding: JSONEncoding.default, headers: headers).responseJSON { response in
            let cCatData = JSON(response.result.value ?? [])
            completionHandler(cCatData, response.response?.statusCode)
        }
    }
    

    无论哪种方式,您都可以这样做:

    Api.getCategories(catId) { json, statusCode in 
        guard statusCode == 200 else {
            print("status code not 200! \(statusCode)")
            return
        }
    
        // if you got here, the status code must have been 200
    }
    

    【讨论】:

      【解决方案2】:

      所以基本上你想要的是这样的:

      func returnStatusCode(_ urlPath: String, parameters: [String: AnyObject]? = nil, headers: [String: String]? = nil, encoding: ParameterEncoding = URLEncoding.default, completion: @escaping (_ statusCode: Int, _ responseData: [String: AnyObject]?) -> Void) {
      
          // you can omit 'encoding:' if you'll set it to default since it will be default by default. \o/
          Alamofire.request(urlPath, method: .get, parameters: parameters, encoding: encoding, headers: headers).responseJSON { (response) in
      
              if response.result.isSuccess, let returnObject = response.result.value as? [String: AnyObject], let statusCode = response.response?.statusCode {
                  // do something...
      
                  completion(statusCode, returnObject)
              }
          }
      }
      

      使用回调单独处理状态码

      【讨论】:

      • 那么如何获取其他文件中的状态码和数据呢?
      • 我更新了我的帖子。请检查。此代码使用 swift 3.0 alamofire 4.0.1
      • 啊是的好点...但如果成功,它将始终落入代码 200。如果错误,则处理与该错误有关的错误代码。这就是我在这里所做的......但如果你有建议我愿意听。 (y)
      • 好的,我已经删除了 else 块,但这不会阻止他处理 NSError 中的错误代码吗?
      • 当然,他可以添加任何他想要的错误处理,但不要将其与 http 状态码混淆,这是完全不同的事情。
      猜你喜欢
      • 1970-01-01
      • 2016-01-18
      • 2018-07-09
      • 2016-04-16
      • 2015-08-04
      • 2016-02-07
      • 1970-01-01
      • 2015-05-21
      • 1970-01-01
      相关资源
      最近更新 更多