GiGaMaskTime/GIGA/Common/GiGaUserDB/GiGaUserManager.m

109 lines
2.5 KiB
Objective-C
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

//
// GiGaUserManager.m
// GIGA
//
// Created by lianxiang on 2018/8/15.
// Copyright © 2018年 com.giga.ios. All rights reserved.
//
#import "GiGaUserManager.h"
#import "YTKKeyValueStore.h"
#import "GiGaUserDefault.h"
NSString *const GIGA_USER_TABLE = @"user_table";
const static NSInteger GIGADB_USER_VER = 0;//当前数据库版本号
@interface GiGaUserManager()
@property (nonatomic,strong) YTKKeyValueStore *store;
@property (nonatomic,strong) NSMutableArray *userArr;
@property (nonatomic,copy) NSString *userTabId;
@end
@implementation GiGaUserManager
+ (instancetype)shareUser{
static GiGaUserManager *userManager = nil;
static dispatch_once_t once;
dispatch_once(&once, ^{
userManager = [[self alloc] init];
});
return userManager;
}
-(instancetype)init{
self = [super init];
if (self) {
// 打开名为GiGa.db的数据库如果该文件不存在则创新一个新的。
self.store = [[YTKKeyValueStore alloc] initDBWithName:@"GiGa.db"];
[self creatTableByName:GIGA_USER_TABLE];
_userArr = [NSMutableArray new];
[self detectionUserUpgrade];
}
return self;
}
//建表
-(void)creatTableByName:(NSString *)tableName{
[_store createTableWithName:tableName];
}
- (void)saveUser:(GiGaUser *)user{
self.user = user;
NSString *userTableId = [NSString stringWithFormat:@"%@",user.userId];
self.userTabId = userTableId;
//暂定只保留一个用户
[_userArr removeAllObjects];
[_userArr addObject:user];
[_store putObject:_userArr withId:userTableId intoTable:GIGA_USER_TABLE];
[GiGaUserDefault saveUserId:userTableId];
}
//已登录
-(GiGaUser *)getCurrentUser{
NSString *useriD = [GiGaUserDefault getCurentUserId];
NSArray *usrA= [_store getObjectById:useriD fromTable:GIGA_USER_TABLE];
if (usrA && usrA.count > 0) {
self.user = usrA[0];
}
return self.user;
}
//
-(void)loginOut{
self.user = nil;
[GiGaUserDefault removeUserId];
}
- (void)detectionUserUpgrade{
NSInteger oldVerion = [GiGaUserDefault getOldVersion];
if (GIGADB_USER_VER <= oldVerion) {
return;
}
[self upgradUserDBToNew];
[GiGaUserDefault saveDBVersion:GIGADB_USER_VER];
}
-(void)upgradUserDBToNew{
if (_userArr.count <= 0) {
GILog(@"there is no user yet");
return;
}
[_store putObject:_userArr withId:self.userTabId intoTable:GIGA_USER_TABLE];
}
@end