这里用简单的例子讲解一下,CodingNet数据模型:
按如下图打一个断点,我们来追踪这个操作,并且将客户端本地缓存和服务器等等交互连串起来
接着我们在介绍页里点击登录,会发现上面的运行情况
可以知道:
- (void)viewWillAppear:(BOOL)animated{
[super viewWillAppear:animated];
[self.navigationController setNavigationBarHidden:YES animated:YES];
[self refreshCaptchaNeeded]; // 这里产生了对服务器的Get请求
[self refreshIconUserImage];
}
接着请求操作中:
[self GET:aPath parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
id error = [self handleResponse:responseObject autoShowError:autoShowError];
if (error) {
responseObject = [NSObject loadResponseWithPath:localPath];
block(responseObject, error);
}else{
if ([responseObject isKindOfClass:[NSDictionary class]]) {
if ([responseObject[@"data"] isKindOfClass:[NSDictionary class]]) {
if (responseObject[@"data"][@"too_many_files"]) {
if (autoShowError) {
[NSObject showHudTipStr:@"文件太多,不能正常显示"];
}
}
}
// 这里调用了Login 数据模型的方法
[NSObject saveResponseData:responseObject toPath:localPath];
}
block(responseObject, nil);
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
!autoShowError || [NSObject showError:error];
id responseObject = [NSObject loadResponseWithPath:localPath];
block(responseObject, error);
}];
具体实现:
//网络请求
+ (BOOL)saveResponseData:(NSDictionary *)data toPath:(NSString *)requestPath{
User *loginUser = [Login curLoginUser];
if (!loginUser) {
return NO;
}else{
requestPath = [NSString stringWithFormat:@"%@_%@", loginUser.global_key, requestPath];
}
if ([self createDirInCache:kPath_ResponseCache]) {
NSString *abslutePath = [NSString stringWithFormat:@"%@/%@.plist", [self pathInCacheDirectory:kPath_ResponseCache], [requestPath md5Str]];
return [data writeToFile:abslutePath atomically:YES];
}else{
return NO;
}
}
还有一些结合,UserDefault和Cookies的机制也是非常非常好
+ (void)doLogin:(NSDictionary *)loginData{
NSArray *cookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies];
[cookies enumerateObjectsUsingBlock:^(NSHTTPCookie * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
NSLog(@"cookies : %@", obj.description);
}];
if (loginData) {
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:[NSNumber numberWithBool:YES] forKey:kLoginStatus];
[defaults setObject:loginData forKey:kLoginUserDict];
curLoginUser = [NSObject objectOfClass:@"User" fromJSON:loginData];
[defaults synchronize];
[Login setXGAccountWithCurUser];
[self saveLoginData:loginData];
}else{
[Login doLogout];
}
}