前提:後臺返回的接口帶etaggit
第一步github
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
方法里加入代碼,也能夠抽成一個方法方便調用或更多其餘設置api
- (void)initCache { NSURLCache *cache = [[NSURLCache alloc] initWithMemoryCapacity:4 * 1024 * 1024 diskCapacity:20 * 1024 * 1024 diskPath:@"NSURLCache"]; [NSURLCache setSharedURLCache:cache]; }
我這裏使用的是系統自帶的NSURLCache,好處就是他會自動處理存,你只須要處理取就好了,可能以爲系統存,會優化一點吧,緩存
固然你也能夠使用性能比較好的一些第三方來存取,好比YYCache、PINCache等app
設置AFN性能
[_manager.requestSerializer setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
要是不 這樣設置的話,它會一直返回200給你,固然若是大家跟後臺約定了緩存失效的時間,那也能夠不用看什麼304,直接判斷本地緩存的有效期就好了優化
而後咱們就開始加入etag,存入etag,304時從緩存取了url
if (method == RequestMethodGet) { YYCache *urlCache = [YYCache cacheWithName:@"EtagCache"]; NSString* etag = (NSString *)[urlCache objectForKey:cacheKey]; if (etag != nil){ // get時若是有etag,咱們就加入到headerField中 [_manager.requestSerializer setValue:etag forHTTPHeaderField:@"If-None-Match"]; } task = [_manager GET:api parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) { if ([(NSHTTPURLResponse *)task.response allHeaderFields][@"Etag"]) { // 請求成功後,若是有etag,咱們就存起來 [urlCache setObject:[(NSHTTPURLResponse *)task.response allHeaderFields][@"Etag"] forKey:cacheKey]; } respondSuccessBlock(task, responseObject); } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) { if ([(NSHTTPURLResponse *)task.response statusCode] == 304) { // 返回304咱們就從緩存中取數據 NSCachedURLResponse* cachedResponse = [[NSURLCache sharedURLCache] cachedResponseForRequest:task.currentRequest]; id responseObject = [_manager.responseSerializer responseObjectForResponse:cachedResponse.response data:cachedResponse.data error:nil]; respondSuccessBlock(task,responseObject); } else { respondErrorBlock(task, error); } }]; }