2016-12-15 225 views
1

我正在與JWT令牌和Alamofire一起使用Swift。我的問題是,當請求返回nil時,我希望request-method運行refreshToken()方法並重試HTTP請求。我的代碼看起來像這樣。我試圖自己跑,但沒有成功。 :(完成處理程序內的完成處理程序?

// Internal method used for the HTTP methods 
private func request<A>(resource: Resource<A>, method: Alamofire.HTTPMethod, parameters: [String:String], completion: @escaping (A?) ->()) { 

let requestUrl = self.baseurl.absoluteString + resource.url.absoluteString + "?token=" + self.loginManager.getFromKeychain().token! 

    Alamofire.request(requestUrl, method: method, parameters: parameters).response { response in 

     // Check if response need reauth 
     if(response.response?.statusCode == 401 || response.response?.statusCode == 400) { 

      self.refreshToken(completion: { result in 

       if(result) { 
        print("Token got refreshed") 

        // How do i make the request again? 

       } 

      }) 

     } 

     guard let data = response.data else { 
      completion(nil) 
      return 
     } 

     completion(resource.parse(data as NSData)) 

    } 

} 
+0

你可以給你的主要方法完成處理程序添加更多的參數,你的方法再次提出請求時,你會得到您的401狀態代碼 – guiltance

+0

您能給我舉一個例子嗎? –

回答

1

你的方法成爲:

private func request<A>(resource: Resource<A>, method: Alamofire.HTTPMethod, parameters: [String:String], completion: @escaping (A?, error: Int?) ->()) { 

    let requestUrl = self.baseurl.absoluteString + resource.url.absoluteString + "?token=" + self.loginManager.getFromKeychain().token! 

    Alamofire.request(requestUrl, method: method, parameters: parameters).response { response in 

     // Check if response need reauth 
     if(response.response?.statusCode == 401 || response.response?.statusCode == 400) { 
      completion(nil, response.response?.statusCode) 
     } 

     guard let data = response.data else { 
      completion(nil, nil) 
      return 
     } 

     completion(resource.parse(data as NSData, nil) 

    } 
} 

哪裏叫

func myMethod(resource: Resource<A>, method: Alamofire.HTTPMethod, parameters: [String:String]) { 
    self.request(resource: resource, method: method, parameters: parameters) { (result, errorCode) in 
    if let errorCode = errorCode { 
     self.refreshToken(completion: { res in 
      if(res) { 
       print("Token got refreshed") 

       // How do i make the request again? 
       self.myMethod(resource: resource, method: method, parameters: parameters) 
      } 
     }) 
    } 
    else if let result = result { 
     //ok got a result 
    } 
} 
+0

感謝您的幫助! –