转自:http://blog.sina.com.cn/s/blog_9693f61a01016t4w.html
在IOS应用程序开发中,为了减少与服务端的交互次数,加快用户的响应速度,一般都会在IOS设备中加一个缓存的机制。使用缓存的目的是为了使用的应用程序能更快速的响应用户输入,是程序高效的运行。有时候我们需要将远程web服务器获取的数据缓存起来,减少对同一个url多次请求。下面将介绍如何在IOS设备中进行缓存。
#import
@interface ViewController : UIViewController
@property (strong,nonatomic) NSURLConnection*connection;
@property (strong, nonatomic) NSURLCache *urlCache;
@property (strong, nonatomic) NSURL*url;
@property (strong, nonatomic) NSMutableURLRequest *request;
- (IBAction)reloadWebView:(UIButton *)sender;
@end
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad
{
}
这个例子中,我们请求url为http://blog.sina.com.cn/u/2526279194的网站。如果这个url被缓存了,我们直接从缓存中获取数据,否则从http://blog.sina.com.cn/u/2526279194站点上重新获取数据。我们设置了缓存大小为1M。
- (IBAction)reloadWebView:(UIButton *)sender {
}
使用下面代码,我将请求的过程打印出来
- (void)
}
- (NSURLRequest *)connection:(NSURLConnection *)connection
}
- (void)connection:(NSURLConnection *)connection
}
-(NSCachedURLResponse *)connection:(NSURLConnection *)connection
}
- (void)connectionDidFinishLoadi
}
- (void)connection:(NSURLConnection *)connection
}
@end
第一次打印结果如下
2013-01-31 15:28:29.923NSURLCacheDemo[27848:907] 即将发送请求
2013-01-31 15:28:30.043NSURLCacheDemo[27848:907] 将接收输出
2013-01-31 15:28:30.045NSURLCacheDemo[27848:907] 接受数据
2013-01-31 15:28:30.047NSURLCacheDemo[27848:907] 数据长度为= 30047
2013-01-31 15:28:30.095NSURLCacheDemo[27848:907] 接受数据
2013-01-31 15:28:30.098NSURLCacheDemo[27848:907] 数据长度为= 3575
2013-01-31 15:28:30.102NSURLCacheDemo[27848:907] 接受数据
2013-01-31 15:28:30.104NSURLCacheDemo[27848:907] 数据长度为= 1482
2013-01-31 15:28:30.105NSURLCacheDemo[27848:907] 将缓存输出
2013-01-31 15:28:30.107NSURLCacheDemo[27848:907] 请求完成
第二次点击打印结果如下
2013-01-31 15:28:31.599NSURLCacheDemo[27848:907] 如果有缓存输出,从缓存中获取数据
2013-01-31 15:28:31.607NSURLCacheDemo[27848:907] 即将发送请求
2013-01-31 15:28:31.840NSURLCacheDemo[27848:907] 将接收输出
2013-01-31 15:28:31.843NSURLCacheDemo[27848:907] 接受数据
2013-01-31 15:28:31.845NSURLCacheDemo[27848:907] 数据长度为= 35104
2013-01-31 15:28:31.846NSURLCacheDemo[27848:907] 请求完成