---
title: "AFNetWorking and SDUrlCache 缓存http请求"
author: "zhy584520"
date: "2014-11-03T14:25:16Z"
tags: []
categories: ["移动开发"]
slug: "afnetworking-and-sdurlcache-http"
draft: false
lastmod: "2014-11-03T14:25:42Z"
id: 2151864
url: "https://zhy584520.iteye.com/blog/2151864"
---

```
     SDURLCache *urlCache = [[SDURLCache alloc]
     initWithMemoryCapacity:1024*1024*2   // 2MB mem cache
     diskCapacity:1024*1024*15 // 15MB disk cache
     diskPath:[SDURLCache defaultCachePath]];
     [urlCache setMinCacheInterval:1];
     [NSURLCache setSharedURLCache:urlCache];
     
     NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.baidu.com"]];
     AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
     [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
     NSLog(@"从服务端获取数据：%@",operation.responseString);
     } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
     if ([urlCache isCached:[NSURL URLWithString:@"http://www.baidu.com"]]) {
     
     }
     NSCachedURLResponse *resp = [urlCache cachedResponseForRequest:request];
     NSString  *str = [[NSString alloc] initWithData:resp.data encoding:NSUTF8StringEncoding];
     NSLog(@"从缓存中获取数据：%@",str);
     }];
     [operation start];
```