- NSCache 是内存缓存,可以暂时储存到内存,当程序退出时储存的内容就会消失
-(NSCache *)cache
{
if (!_cache) {
_cache = [[NSCache alloc] init];
_cache.countLimit = 100;
_cache.totalCostLimit = 5 * 1024 * 1024; // 5M
}
return _cache;
}
NSData *cachedData = [_cache objectForKey:@"REQUEST"];
if (cachedData) {
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:cachedData options:kNilOptions error:nil];
NSLog(@"cachedData -%@",dict);
} else {
NSLog(@"暂无缓存");
__weak typeof(self) weakSelf = self;
NSURL *url = [NSURL URLWithString:@"https://weatherapi.market.xiaomi.com/wtr-v3/weather/all?latitude=110&longitude=112&isLocated=true&locationKey=weathercn%3A101010100&days=15&appKey=weather20151024&sign=zUFJoAR2ZVrDy1vF3D07&romVersion=7.2.16&appVersion=87&alpha=false&isGlobal=false&device=cancro&modDevice=&locale=zh_cn"];
NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:15.0];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
if (error) {
NSLog(@"error - %@",error);
} else {
[weakSelf.cache setObject:data forKey:@"REQUEST"];
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
NSLog(@"dict -%@",dict);
}
}];
[task resume];
}