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

标签 ios swift mvvm

我在我的项目中使用 moya 进行 api 调用。 我有一个 BaseViewController。在这个 Controller 中,我编写了一些使用每个 View Controller 的常用方法。

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

所有 View 模型均派生自 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.")
        }
    }
        }

    }
}

最佳答案

我找到了解决方案:

在 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/

相关文章:

wpf - 如果我创建一个 ViewModel,我是否需要以 MVVM 模式为其创建模型?

ios - 禁用 UIWebView 的放大缩小功能

ios - 在 React Native iOS 中的图像顶部呈现具有透明背景的文本框

ios - 使用 NSTimeInterval 创建 dispatch_time_t

Swift:获取字符串宽度以在 swift 2.2 中制作框架(使用 CGRect)

c# - wpf excel 喜欢网格编辑吗?

Wpf MVVM,如何将 ImageSource 转换为字节数组

ios - 如何使用 Swift 使用此代码片段为 iOS 应用程序初始化 SDK?

ios - 如何解决swift 3中标签中最后一个值的重叠问题

swift - View 更改后保留单元格选择