2016-08-24 56 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) 
    } 
相關問題