class APIInterceptor: RequestInterceptor {
let apiKey = "YOUR_API_KEY"
func adapt(_ urlRequest: URLRequest, for session: Session, completion: @escaping (Result) -> Void) {
var urlRequest = urlRequest
urlRequest.setValue(apiKey, forHTTPHeaderField: "X-API-Key")
completion(.success(urlRequest))
}
}
Session
时,将拦截器作为参数传入,例如:let configuration = URLSessionConfiguration.af.default
let session = Session(configuration: configuration, interceptor: APIInterceptor())
session.request
方法而不是 AF.request
方法,例如:session.request("https://api.example.com/data").responseJSON { response in
debugPrint(response)
}
如果以上步骤都正确无误,但仍然无法调用拦截器,可能是网络请求库本身存在Bug,可以尝试升级 Alamofire 版本或者寻求其他解决方法。