在每个Alamofire请求之前/之后调用一个函数 [英] Call a function before/after each Alamofire request

查看:71
本文介绍了在每个Alamofire请求之前/之后调用一个函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否仍然可以使用Alamofire和iOS实现类似于中间件的功能。

I'd like to know if there is anyway to implement something akin to middleware using Alamofire and iOS.

我有很多类似的API调用,它们都需要有效的json网络令牌进行身份验证。我想在每个API调用之前执行相同的验证,或者在任何API调用失败时交替执行相同的纠正措施。有没有一种方法可以配置它,而不必将相同的代码块复制并粘贴到所有API调用的开头或结尾?

I've got a slew of API calls that are all pretty similar, and they all require a valid json web token for authentication. I want to perform the same validation before every API call, or alternately take the same corrective action when any API call fails. Is there a way I can configure it so that I don't have to copy and paste the same chunk of code onto the beginning or end of all of the API calls?

推荐答案

包装器类

您可以为您的请求创建包装器。

You can create a wrapper for your request.

class AlamofireWrapper {
    static func request(/*all the params you need*/) {
        if tokenIsValidated() { //perform your web token validation
            Alamofire.request//...
            .respone { /*whatever you want to do with the response*/ }
        }
    }
}

您可以像这样使用它,而不必再次复制并粘贴相同的代码。 / p>

You can use it like this wihtout having to copy and paste the same code again.

AlamofireWrapper().request(/*params*/)

扩展

未经测试。您可以向Alamofire添加扩展名

This is not tested. You can add an extension to Alamofire

extension Alamofire {
    func validatedRequest(/*all the params you need*/) {
        if tokenIsValidated() { //perform your web token validation
            Alamofire.request//...
            .respone { /*whatever you want to do with the response*/ }
        }
    }
}

并像这样使用

Alamofire.validatedRequest(/*params*/)

这篇关于在每个Alamofire请求之前/之后调用一个函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆