#import "ViewController.h"
@interface ViewController ()
@property (weak, nonatomic) IBOutlet UIImageView *imageView;
@property (nonatomic, copy) NSString *etag;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
NSURL *url = [NSURL URLWithString:@"http://localhost/itcast/images/head1.png"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:1 timeoutInterval:15];
if (self.etag) {
[request setValue:self.etag forHTTPHeaderField:@"If-None-Match"];
}
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
NSLog(@"%@ -- %zd",response,data.length);
if (httpResponse.statusCode == 304) {
NSCachedURLResponse *cacheResponse = [[NSURLCache sharedURLCache]cachedResponseForRequest:request];
data = cacheResponse.data;
NSLog(@"本地缓存");
}
UIImage *image = [UIImage imageWithData:data];
self.imageView.image = image;
self.etag = httpResponse.allHeaderFields[@"Etag"];
NSLog(@"etag == %@",self.etag);
}];
}
@end