gpt4 book ai didi

ios - 如何覆盖 Alamofire SessionManager 以修改响应以添加 header ?

转载 作者:行者123 更新时间:2023-11-28 14:31:12 26 4
gpt4 key购买 nike

所以,我正在使用 Alamofire 发出一些 HTTP 请求,并且我正在尝试使用缓存策略,但服务器的 header 中没有“Cache-Control”标志。所以我想使用 session 管理器添加这个标志 delegate method dataTaskWillCacheResponse 基于此answer here.

为了做到这一点,我想创建一个带有 SessionManager 静态共享实例的类(我不想在 AppDelegate 上创建一个全局变量。我认为这不是一个好的做法)并在此类中重写委托(delegate)方法,但我做不到。

这是我的代码:

public class Manager: SessionDelegate {
var manager: SessionManager?
weak var sessionDelegate: SessionDelegate?
override init() {
super.init()
let configuration = URLSessionConfiguration.default
configuration.urlCache = URLCache(memoryCapacity: 20 * 1024 * 1024, diskCapacity: 100 * 1024 * 1024, diskPath: nil)
configuration.requestCachePolicy = .returnCacheDataElseLoad
configuration.timeoutIntervalForRequest = 35
self.manager = SessionManager(configuration: configuration)
self.manager = Alamofire.SessionManager(configuration: configuration)
self.manager?.delegate = self
}
}

self.manager.delegate = self 上我得到错误:无法分配给属性:'delegate' is a 'let' constant

我对 Swift 和 Alamofire 比较陌生。我究竟做错了什么?我怎样才能实现我想要做的事情?

编辑:我看到我无法创建单例,但我能够使用共享实例并覆盖方法。检查下面的答案

最佳答案

经过更多的研究,我发现了一些东西:
1 - Advanced usage override closures
2 - Found this answer that creates a Session Manager
3 - Found this solutiondataTaskWillCacheResponse 委托(delegate)方法中为我的响应添加 header 。

这是我的解决方案:

class MyService {
static let shared = MyService()

//The manager with the cache policy
private let manager: Alamofire.SessionManager = {
let configuration = URLSessionConfiguration.default
configuration.requestCachePolicy = .useProtocolCachePolicy
configuration.timeoutIntervalForRequest = 35
return Alamofire.SessionManager(configuration: configuration)
}()

init() {
let delegate: Alamofire.SessionDelegate = manager.delegate
//Overriding delegate to add headers
delegate.dataTaskWillCacheResponseWithCompletion = { session, datatask, cachedResponse, completion in
let response = cachedResponse.response as! HTTPURLResponse
var headers = response.allHeaderFields as! [String: String]
print(headers.keys.contains("Cache-Control"))
headers["Cache-Control"] = "max-age=30"
let modifiedResponse = HTTPURLResponse(
url: response.url!,
statusCode: response.statusCode,
httpVersion: "HTTP/1.1",
headerFields: headers)

let modifiedCachedResponse = CachedURLResponse(
response: modifiedResponse!,
data: cachedResponse.data,
userInfo: cachedResponse.userInfo,
storagePolicy: cachedResponse.storagePolicy)
completion(modifiedCachedResponse)
}
}
}

关于ios - 如何覆盖 Alamofire SessionManager 以修改响应以添加 header ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51252963/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com