Set cache time AFNetworking swift 2

2019-08-13 01:25发布

I am loading data using code 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.

2条回答
爷的心禁止访问
2楼-- · 2019-08-13 01:36

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

A sample in Objective 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;
}];
查看更多
看我几分像从前
3楼-- · 2019-08-13 01:53

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:

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)
查看更多
登录 后发表回答