我正在我的应用程序中实现授权,其中我使用Alamofire 4.0.我有一个令牌可以添加到我发出的每个HTTP请求的头中,如果响应代码是401,我必须签入每个请求,在这种情况下,我必须注销用户。
最佳实践是什么?有没有一种简单的方法将这种行为添加到每个请求中?
我在这里查看了会话管理器和请求适配器,创建单例请求管理器并使用它来创建请求非常容易,但是我找不到为401响应代码添加集中验证的好方法。这必须是一个一般的验证,如果它失败,我注销用户,如果它通过,我将让处理请求的人谁提出的请求。
我希望的目标是在我的代码中只有一个点检查401错误代码。
我四处寻找,没有找到一个令人满意的答案,关于如何做这件事,有什么建议吗?
let alamofireManager: SessionManager = {
let configuration = URLSessionConfiguration.default
configuration.httpMaximumConnectionsPerHost = AppConstants.maxSimultaneousDownloads
configuration.requestCachePolicy = .reloadIgnoringLocalCacheData
return SessionManager(configuration: configuration)
}()
self.alamofireManager.request(UrlString)
.responseJSON { response in
print("response: \(response)")
guard response.result.isSuccess else {
//Request fails here. Trigger here to log out the user
return
}
if let JSON = response.result.value {
print("Successful")
//or check response code here
}
}