- (void)cachenetworkWithURL: (NSString *)urlString
parameter: (NSDictionary *)paraDic
susccess: (void(^)(id obj)) succeee
fail:(void(^)(NSError *error))fail{
// NSURLSession 配置
NSURLSessionConfiguration *configuration = [NSURLSessionConfigurationdefaultSessionConfiguration];
//创建 sessionManager
AFURLSessionManager *manager = [[AFURLSessionManageralloc] initWithSessionConfiguration:configuration];
//创建请求
NSMutableURLRequest *request = [[AFHTTPRequestSerializerserializer] multipartFormRequestWithMethod:@"POST"URLString:urlString parameters:paraDicconstructingBodyWithBlock:nilerror:nil];
//创建请求任务
NSURLSessionDataTask *dataTask = [manager dataTaskWithRequest:request completionHandler:^(NSURLResponse *_Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
//缓存文件路径
NSString *cachePath = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask, YES)firstObject] stringByAppendingString:urlString.md5];
//如果有 error ,请求失败
//反之,请求成功
if (error) {
NSLog(@"网络请求失败");
//请求失败,从本地把缓存数据取出
id obj = [NSDictionarydictionaryWithContentsOfFile:cachePath];
if (obj) {
succeee(obj[@"data"]);
}else{
fail(error);
}
}else {
//把object存储到本地
//读写
[@{@"data": responseObject}writeToFile:cachePath atomically:YES];
succeee(responseObject);
}
}];
//开启任务
[dataTaskresume];
}