【问题标题】:Swift: How can I implement api response validation with most elegant way?Swift:如何以最优雅的方式实现 api 响应验证?
【发布时间】:2019-02-22 06:25:05
【问题描述】:

我在我的项目中使用 moya 进行 api 调用。 我有一个 BaseViewController。在这个控制器中,我编写了一些常用的方法来使用每个视图控制器。

BaseViewController 有一个名为 BaseViewModel 的视图模型。

所有视图模型都派生自 BaseViewModel。

我想在我的所有 api 完成后调用一个带有 statusCode 参数的函数。 然后在 baseviewcontroller 中,我想获取我传递给函数的状态码。 我将函数声明为属性,但我不知道如何使用它。

这里是代码。

    class BaseViewModel {

    var onApiFetchCompleted: (Int)?
    var isLoading = false {
        didSet{
            self.uploadLoadingStatus?()
        }
    }
    var uploadLoadingStatus : (() -> (Void))?
}

    class DataViewModel: BaseViewModel {
        func get(_ params: [String], completion: @escaping (Response) -> ()){
            var response = Response()!
            ApiProvider.request(.request(params: params)) { result in
            switch result {
            case let .success(moyaResponse):
                if moyaResponse.statusCode == 200 {
                    let json = try! moyaResponse.mapJSON() as! [String:Any]
                    response = Mapper<Response>().map(JSON: json)!
                }
                response.statusCode = moyaResponse.statusCode
                super.onApiFetchCompleted(response.statusCode)
            case let .failure(error):
                print("")
            }
            completion(response)
        }
    }
}
    class BaseVC: UIViewController {

    lazy private var viewModel: BaseViewModel = {
        return BaseViewModel()
    }()
    typealias onConfirmAccepted = ()  -> Void
    typealias onConfirmDismissed = ()  -> Void
    override func viewDidLoad() {
        super.viewDidLoad()

        viewModel.onApiFetchCompleted = {
        //here i want to use passed statusCode parameter to function
        if statusCode != 200 {
        if statusCode == 403 {
            returnToLogin(title: "Information", message: "Session Expired!")
        }
        else if statusCode == 401 {
            self.showError(title: "Unauthorized Access", message: "You have not permission to access this data!")
        }
        else {
            self.showError(title: "Error", message: "Unexpected Error. Call your system admin.")
        }
    }
        }

    }
}

【问题讨论】:

    标签: ios swift mvvm


    【解决方案1】:

    我找到了解决方案:

    在 BaseViewModel 中,我声明了一个函数:

    var onApiFetchCompleted: ((_ statusCode: Int) -> ())?
    

    在 baseViewController 中:

     func onApiFetchCompleted(statusCode: Int)  {
        //do what you want with status code 
     }
    override func viewDidLoad() {
        super.viewDidLoad()
    
        viewModel.onApiFetchCompleted = { (statusCode:Int) -> () in
            self.onApiFetchCompleted(statusCode: statusCode)
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2011-10-03
      • 2021-03-05
      • 1970-01-01
      • 1970-01-01
      • 2015-07-14
      • 2018-06-27
      • 2013-06-28
      • 2013-03-26
      • 2010-10-21
      相关资源
      最近更新 更多