2016-08-24 58 views
0

我想知道是否有任何实现类似于使用Alamofire和iOS的中间件的东西。每个Alamofire请求之前/之后调用一个函数

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

+2

围绕您打来的Alamofire方法创建一个包装? – nhgrif

回答

2

包装类

您可以为您的要求的包装。

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*/ } 
     } 
    } 
} 

您可以使用它像这样wihtout无需复制和重新粘贴相同的代码。

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

扩展

这不是测试。您可以添加一个扩展到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*/) 
1

如果你想在一个共同的头连接到所有的呼叫,您可以使用Alamofire.manager。所有Alamofire.request设置使用Alamofire.manager

var defaultHeaders = Alamofire.Manager.sharedInstance.session.configuration.HTTPAdditionalHeaders ?? [:] 
defaultHeaders["Accept-Language"] = "zh-Hans" 

let configuration = NSURLSessionConfiguration.defaultSessionConfiguration() 
configuration.HTTPAdditionalHeaders = defaultHeaders 

let manager = Alamofire.Manager(configuration: configuration) 

一个共享实例验证令牌,我不喜欢这样在执行我的所有请求的网络类。

func authHeaders() -> [String: String] { 
    let headers = [ 
     "Authorization": "Token \(UserManager.sharedInstance.token)", 
    ] 
} 
Alamofire.request(.GET, "https://myapi/user", headers: authHeaders()) 
    .responseJSON { response in 
     debugPrint(response) 
    } 
相关问题