设置缓存时间AFNetworking swift 2

时间:2015-12-16 12:31:14

标签: ios swift caching 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)
        })

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

2 个答案:

答案 0 :(得分:1)

对于来自Swift宗教的人,我使用从AFHTTPSessionManager调用self.setDataTaskWillCacheResponseBlock:并修改AFNetworking 3.0响应标头值的方法编写了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
    })
  }
}

现在您的使用非常简单:

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

答案 1 :(得分:0)

您可以通过更改响应的标头字段,使用setDataTaskWillCacheResponseBlock解决此问题。您需要ExpiresExpires个字段。

目标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;
}];