如何覆盖Alamofire SessionManager以修改响应以添加标头?

时间:2018-07-09 19:43:53

标签: ios swift alamofire nsurlcache

因此,我正在使用Alamofire发出一些HTTP请求,并且尝试使用缓存策略,但是服务器的标头中没有“ Cache-Control”标志。因此,我想基于此delegate method

使用会话管理器answer here. dataTaskWillCacheResponse添加此标志

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

这是我的代码:

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'是'let'常量

我在Swift和Alamofire中相对较新。我究竟做错了什么?而我该如何实现自己的目标?

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

1 个答案:

答案 0 :(得分:1)

研究更多之后,我发现了一些东西:
1-Advanced usage override closures
2-Found this answer that creates a Session Manager
3-Found this solution,它在dataTaskWillCacheResponse委托方法的响应中添加标题。

这是我的解决方案:

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)
        }
    }
}