网络:GET 的使用

#import "ViewController.h"

@interface ViewController ()
@property (weak, nonatomic) IBOutlet UIImageView *imageView;
@property (nonatomic, copy) NSString *etag;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    // NSURL
    NSURL *url = [NSURL URLWithString:@"http://localhost/itcast/images/head1.png"];
    // NSURLRequest 请求
//    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:1 timeoutInterval:15];


    // 面试的时候问缓存怎么做?系统就可以
    // 要做到,如果服务器资源发生改变,我就下载。如果没有发生改变,就使用本地缓存
    // Etag = "\"b2d4-4ddbf42ea8380\""; 蓝色头像
    // Etag = "\"b690-4ddbf42ea8380\""; 粉红色头像
    // 如果服务器资源跟本地资源不匹配,就会返回新的数据
    // 如果服务器资源跟本地资源是一样的,返回 304,判断状态码自己去取本地缓存
    // 告诉服务器当前的Etag值
    // 先判断Etag 是否有值
    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);
        // 如果服务器返回状态码是304 证明服务器文件没有发生改变
        if (httpResponse.statusCode == 304) {
            // 取出缓存数据
         NSCachedURLResponse *cacheResponse = [[NSURLCache sharedURLCache]cachedResponseForRequest:request];
            data = cacheResponse.data;
            NSLog(@"本地缓存");
        }

        // 接到二进制数据
        // 转化成UIImage
        UIImage *image = [UIImage imageWithData:data];
        // 显示出来
        self.imageView.image = image;

        // 保存当前请求的Etag 值
        self.etag = httpResponse.allHeaderFields[@"Etag"];
        NSLog(@"etag == %@",self.etag);
    }];

}
@end
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值