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

BaseViewController有一个称为BaseViewModel的 View 模型。

所有 View 模型都派生自BaseViewModel。

我想在所有API完成后调用带有statusCode参数的函数。
然后在baseviewcontroller中,我想获取传递给函数的statuscode。
我宣布功能为属性(property),但我不知道如何使用它。

这是代码。

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

    }
}

最佳答案

我找到了解决方案:

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

关于ios - Swift:如何以最优雅的方式实现api响应验证?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/54821219/

10-10 02:36