Swift:如何以最优雅的方式实现api响应验证?

时间:2019-02-22 06:25:05

标签: ios swift mvvm

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

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

所有视图模型均源自BaseViewModel。

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

这是代码。

    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.")
        }
    }
        }

    }
}

1 个答案:

答案 0 :(得分:0)

我找到了解决方法:

在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)
    }
}