设置缓存时间AFNetworking swift 2

时间:2020-12-07 20:24:50

I am loading data using code AFNetworking

我正在使用代码AFNetworking加载数据

let manager = AFHTTPRequestOperationManager()
    manager.requestSerializer.cachePolicy = NSURLRequestCachePolicy.ReturnCacheDataElseLoad
    manager.responseSerializer = AFHTTPResponseSerializer()

    let testUrl = "https://www.google.com/maps/vt/pb=!1m8!3m7!1m2!1u2816!2u5888!2m2!1u1536!2u512!3i6!2m3!1e0!2sm!3i333!2m20!1e2!2spsm!4m2!1sgid!2sWejnA6yw2AIgHrbvnAUOAg!4m2!1ssp!2s1!8m11!13m9!2sa!15b1!18m5!2b1!3b0!4b1!5b0!6b0!19b1!19u12!3m2!2sen!5e1105!4e4!11m2!1e2!2b1&authuser=0"

    manager.GET(testUrl,
            parameters: nil,
            success: { (operation: AFHTTPRequestOperation!, responseObject: AnyObject!) in
                print("afnetworking GET success1")
            },
            failure: { (operation: AFHTTPRequestOperation?,error: NSError!) in
                print("afnetworking GET 1  - Error: " + error.localizedDescription)
        })

When data is in cache, its giving me data from cache...its fine,
but how can I
1)- Set cache policy, to cache only for 1 hour
2)- When server haven't Caching headers its not caching, cache the data for an hour too for this case also.

当数据在缓存中时,它从缓存中给我数据......很好,但我怎么能1) - 设置缓存策略,只缓存1小时2) - 当服务器没有缓存头时它不缓存,缓存对于这种情况也是一小时的数据。

2 个解决方案

#1


1  

For the guys from Swift religion, I wrote AFHTTPSessionManager extension with method which calls self.setDataTaskWillCacheResponseBlock: from AFNetworking 3.0 and modifies Cache-Control response header value:

对于来自Swift宗教的人,我编写了AFHTTPSessionManager扩展,其方法是从AFNetworking 3.0调用self.setDataTaskWillCacheResponseBlock:并修改Cache-Control响应头值:

extension AFHTTPSessionManager {
  //duration in seconds
  func forceCacheResponse(duration:Int) {
    self.setDataTaskWillCacheResponseBlock({
      (session:NSURLSession, task:NSURLSessionDataTask, proposedResponse:NSCachedURLResponse) -> (NSCachedURLResponse) in
      if let response = proposedResponse.response as? NSHTTPURLResponse {
        var headers = response.allHeaderFields as! [String:String]
        headers["Cache-Control"] = String(format: "max-age=%@", arguments: [duration])

        let modifiedResponse = NSHTTPURLResponse(URL: response.URL!, statusCode: response.statusCode, HTTPVersion: "1.1", headerFields: headers)
        if (modifiedResponse != nil) {
          let cachedResponse = NSCachedURLResponse(response: modifiedResponse!, data: proposedResponse.data, userInfo: proposedResponse.userInfo, storagePolicy: NSURLCacheStoragePolicy.Allowed)
          return cachedResponse
        }
      }

      return proposedResponse
    })
  }
}

Now you have very simple usage:

现在你的用法非常简单:

let manager = AFHTTPSessionManager()
manager.forceCacheResponse(604800)

#2


0  

You can solve it with setDataTaskWillCacheResponseBlock by changing response's header fields. You need Expires and Expires fields.

您可以通过更改响应的标头字段来使用setDataTaskWillCacheResponseBlock解决它。您需要Expires和Expires字段。

A sample in Objective C:

目标C中的一个示例:

[manager setDataTaskWillCacheResponseBlock:^NSCachedURLResponse *(NSURLSession *session, NSURLSessionDataTask *dataTask, NSCachedURLResponse *proposedResponse)
{
    NSHTTPURLResponse *resp = (NSHTTPURLResponse*)proposedResponse.response;
    NSMutableDictionary *newHeaders = [[resp allHeaderFields] mutableCopy];
    if (newHeaders[@"Cache-Control"] == nil) {
        newHeaders[@"Cache-Control"] = @"public";
    }

    NSHTTPURLResponse *response2 = [[NSHTTPURLResponse alloc] initWithURL:resp.URL statusCode:resp.statusCode HTTPVersion:@"1.1" headerFields:newHeaders];
    NSCachedURLResponse *cachedResponse2 = [[NSCachedURLResponse alloc] initWithResponse:response2
                                                     data:[proposedResponse data]
                                                 userInfo:[proposedResponse userInfo]
                                            storagePolicy:NSURLCacheStorageAllowed];
    return cachedResponse2;
}];

#1


1  

For the guys from Swift religion, I wrote AFHTTPSessionManager extension with method which calls self.setDataTaskWillCacheResponseBlock: from AFNetworking 3.0 and modifies Cache-Control response header value:

对于来自Swift宗教的人,我编写了AFHTTPSessionManager扩展,其方法是从AFNetworking 3.0调用self.setDataTaskWillCacheResponseBlock:并修改Cache-Control响应头值:

extension AFHTTPSessionManager {
  //duration in seconds
  func forceCacheResponse(duration:Int) {
    self.setDataTaskWillCacheResponseBlock({
      (session:NSURLSession, task:NSURLSessionDataTask, proposedResponse:NSCachedURLResponse) -> (NSCachedURLResponse) in
      if let response = proposedResponse.response as? NSHTTPURLResponse {
        var headers = response.allHeaderFields as! [String:String]
        headers["Cache-Control"] = String(format: "max-age=%@", arguments: [duration])

        let modifiedResponse = NSHTTPURLResponse(URL: response.URL!, statusCode: response.statusCode, HTTPVersion: "1.1", headerFields: headers)
        if (modifiedResponse != nil) {
          let cachedResponse = NSCachedURLResponse(response: modifiedResponse!, data: proposedResponse.data, userInfo: proposedResponse.userInfo, storagePolicy: NSURLCacheStoragePolicy.Allowed)
          return cachedResponse
        }
      }

      return proposedResponse
    })
  }
}

Now you have very simple usage:

现在你的用法非常简单:

let manager = AFHTTPSessionManager()
manager.forceCacheResponse(604800)

#2


0  

You can solve it with setDataTaskWillCacheResponseBlock by changing response's header fields. You need Expires and Expires fields.

您可以通过更改响应的标头字段来使用setDataTaskWillCacheResponseBlock解决它。您需要Expires和Expires字段。

A sample in Objective C:

目标C中的一个示例:

[manager setDataTaskWillCacheResponseBlock:^NSCachedURLResponse *(NSURLSession *session, NSURLSessionDataTask *dataTask, NSCachedURLResponse *proposedResponse)
{
    NSHTTPURLResponse *resp = (NSHTTPURLResponse*)proposedResponse.response;
    NSMutableDictionary *newHeaders = [[resp allHeaderFields] mutableCopy];
    if (newHeaders[@"Cache-Control"] == nil) {
        newHeaders[@"Cache-Control"] = @"public";
    }

    NSHTTPURLResponse *response2 = [[NSHTTPURLResponse alloc] initWithURL:resp.URL statusCode:resp.statusCode HTTPVersion:@"1.1" headerFields:newHeaders];
    NSCachedURLResponse *cachedResponse2 = [[NSCachedURLResponse alloc] initWithResponse:response2
                                                     data:[proposedResponse data]
                                                 userInfo:[proposedResponse userInfo]
                                            storagePolicy:NSURLCacheStorageAllowed];
    return cachedResponse2;
}];