前言
今天整理一下一般项目中都会有的两个类。它们本身并无难度,主要是对这些细碎的东西梳理一下。都是比较基础的东西,而且代码里的注释比较多,所以主要上代码了。
公共类:PublicFunction
我们可以把项目中一些公用的、基础功能的的东西,且多以类方法的形式定义统一定义在一个公共类里,以便项目开发中调用。
** PublicFunction.h **
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
@interface PublicFunction : NSObject
// app的版本号
+ (NSString *)appVersion;
// 系统版本号
+ (NSString *)OSVersion;
// 设备(iPhone)的固件版本
+ (NSString *)deviceInfo;
// 获取当前的window
+ (UIWindow *)getCurrentWindow;
// 第一次使用APP时保存记号
+ (void)saveAPPFirstUserd:(BOOL)isFirst;
// 判断APP是否是第一次使用
+ (BOOL)isAPPFirstUsered;
// 保存服务器时间和本地时间的差值
+ (void)saveDifferenceWithServerTime:(NSString *)serverTime;
// 获取服务器时间和本地时间的差值
+ (NSTimeInterval)differenceOfLocalAndServer;
// ----- 新添加
// 清除字符串首尾空格
+ (NSString *)clearSpaceOfString:(NSString *)str;
// 清除字符串所有空格
+ (NSString *)clearAllSpaceOfString:(NSString *)str;
@end
** PublicFunction.m **
#import "PublicFunction.h"
#import "sys/utsname.h"
@implementation PublicFunction
// app的版本号
+ (NSString *)appVersion
{
NSDictionary *dict = [[NSBundle mainBundle] infoDictionary];
NSString *appVersion = dict[@"CFBundleShortVersionString"]; // 注意区分CFBundleShortVersionString和CFBundleVersion
if(appVersion.length == 0){
return @"";
}
return appVersion;
}
// 系统版本号
+ (NSString *)OSVersion
{
return [[UIDevice currentDevice] systemVersion];
}
// 设备(iPhone)的固件版本
+ (NSString *)deviceInfo
{
struct utsname systemInfo;
uname(&systemInfo);
NSString *platform = [NSString stringWithCString:systemInfo.machine encoding:NSUTF8StringEncoding];
if (platform.length==0){
return @"";
}
return platform;
}
// 获取当前的window
+ (UIWindow *)getCurrentWindow
{
UIWindow *window = [UIApplication sharedApplication].keyWindow;
if(!window){
window = [[UIApplication sharedApplication].windows firstObject];
}
return window;
}
// 第一次使用APP时保存记号
+ (void)saveAPPFirstUserd:(BOOL)isFirst
{
[[NSUserDefaults standardUserDefaults] setBool:isFirst forKey:@"IsFirstUserAPP"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
// 判断APP是否是第一次使用
+ (BOOL)isAPPFirstUsered
{
return [[NSUserDefaults standardUserDefaults] boolForKey:@"IsFirstUserAPP"];
}
// 保存服务器时间和本地时间的差值
+ (void)saveDifferenceWithServerTime:(NSString *)serverTime
{
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
dateFormat.dateFormat = @"yyyy-MM-dd HH:mm:ss";
NSDate *serverDate = [dateFormat dateFromString:serverTime];
NSTimeInterval server = [serverDate timeIntervalSince1970];
NSDate *localDate = [NSDate date];
NSTimeInterval local = [localDate timeIntervalSince1970];
[[NSUserDefaults standardUserDefaults] setInteger:server-local forKey:@"TimeDifferenceOfLocalAndServer"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
// 获取服务器时间和本地时间的差值
+ (NSTimeInterval)differenceOfLocalAndServer
{
return [[NSUserDefaults standardUserDefaults] integerForKey:@"TimeDifferenceOfLocalAndServer"];
}
// ----- 新添加
// 清除字符串首尾空格
+ (NSString *)clearSpaceOfString:(NSString *)str
{
if(str.length == 0){
return @"";
}
NSString *string = [str stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
return string;
}
// 清除字符串所有空格
+ (NSString *)clearAllSpaceOfString:(NSString *)str
{
if(str.length == 0){
return @"";
}
NSString *string = [str stringByReplacingOccurrencesOfString:@"" withString:@" "];
return string;
}
@end
用户信息类:UserModel
在项目中我们用一个UserModel类来统一管理有关用户信息等的东西。
** UserModel.h **
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
@interface UserModel : NSObject
@property (nonatomic, copy)NSString *userId;
@property (nonatomic, copy)NSString *name;
@property (nonatomic, copy)NSString *nickName;
@property (nonatomic, copy)NSString *sex;
@property (nonatomic, copy)NSString *age;
@property (nonatomic, copy)NSString *mobile;
@property (nonatomic, copy)NSString *email;
@property (nonatomic, copy)NSString *token;
@property (nonatomic, assign)BOOL isLogin; // 登录状态,是否登录
@property (nonatomic, copy)NSString *isSetPayPsd; // 是否设置支付密码
+ (instancetype)shareInstance;
// 保存账号和密码
+ (void)saveAccount:(NSString *)account password:(NSString *)password;
// 保存用户信息到本地
+ (void)saveUserInfoLocal:(NSDictionary *)infoDict;
// 从本地获取用户信息
+ (NSDictionary *)userInfoFromLocal;
// 登录成功后做的一些处理
- (void)handleAfterLoginSuccess:(NSDictionary *)infoDict token:(NSString *)token;
// 退出登录
- (void)handleForLoginOut;
// 弹出登录界面
+ (void)showLoginViewController:(UIViewController *)viewController;
@end
** UserModel.m **
#import "UserModel.h"
#import "LoginViewController.h"
@implementation UserModel
+ (instancetype)shareInstance
{
static UserModel *userModel = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
userModel = [[UserModel alloc] init];
});
return userModel;
}
- (instancetype)init
{
self = [super init];
if(self)
{
// 从本地缓存得到用户信息,成为单例UserModel的内存缓存
[self infoFromDict:[UserModel userInfoFromLocal]];
_isLogin = [[NSUserDefaults standardUserDefaults] boolForKey:@"LoginState"];
_token = [[NSUserDefaults standardUserDefaults] objectForKey:@"UserToken"];
}
return self;
}
// 保存账号和密码
+ (void)saveAccount:(NSString *)account password:(NSString *)password
{
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
if(userDefaults){
[userDefaults setObject:account forKey:@"account"];
[userDefaults setObject:password forKey:@"password"];
[userDefaults synchronize];
}
}
// 保存用户信息到本地
+ (void)saveUserInfoLocal:(NSDictionary *)infoDict
{
if(infoDict.count == 0){
return;
}
NSData *infoData = [NSKeyedArchiver archivedDataWithRootObject:infoDict];
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
[userDefaults setValue:infoData forKey:@"UserInfoData"];
[userDefaults synchronize];
}
// 从本地获取用户信息
+ (NSDictionary *)userInfoFromLocal
{
NSData *infoData = [[NSUserDefaults standardUserDefaults] valueForKey:@"UserInfoData"];
NSDictionary *infoDict = [NSKeyedUnarchiver unarchiveObjectWithData:infoData];
return infoDict;
}
// 退出登录
- (void)handleForLoginOut
{
[self changeLoginState:NO];
_token = nil;
[[NSNotificationCenter defaultCenter] postNotificationName:@"QuitLogin" object:nil];
}
// 登录成功后做的一些处理
- (void)handleAfterLoginSuccess:(NSDictionary *)infoDict token:(NSString *)token
{
if(infoDict.count == 0 || token.length == 0){
return;
}
// 登录状态变为YES
[self changeLoginState:YES];
// 保存token到本地
[self saveToken:token];
// 保存用户信息
[self infoFromDict:infoDict];
[UserModel saveUserInfoLocal:infoDict];
}
// 弹出登录界面
+ (void)showLoginViewController:(UIViewController *)viewController
{
LoginViewController *loginVC = [LoginViewController new];
UINavigationController *loginNavC = [[UINavigationController alloc] initWithRootViewController:loginVC];
[viewController presentViewController:loginNavC animated:YES completion:nil];
}
#pragma mark ---- private method
// 改变登录状态
- (void)changeLoginState:(BOOL)loginState
{
_isLogin = loginState;
[[NSUserDefaults standardUserDefaults] setBool:loginState forKey:@"LoginState"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
// 保存token
- (void)saveToken:(NSString *)token
{
if(token.length == 0){
return;
}
_token = token;
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
[userDefaults setObject:token forKey:@"UserToken"];
[userDefaults synchronize];
}
// 保存用户信息——内存
- (void)infoFromDict:(NSDictionary *)dict
{
if(dict.count == 0){
return;
}
_userId = [dict valueForKey:@"userId"];
_name = [dict valueForKey:@"name"];
_nickName = [dict valueForKey:@"nickName"];
_sex = [dict valueForKey:@"sex"];
_age = [dict valueForKey:@"age"];
_mobile = [dict valueForKey:@"mobile"];
_email = [dict valueForKey:@"email"];
_isLogin = [dict valueForKey:@"isLogin"];
_isSetPayPsd = [dict valueForKey:@"isSetPayPsd"];
}
@end
我们用假数据模拟一下登录成功后的处理:
// 模拟用户登录请求的网络回调数据
NSDictionary *resultInfo = @{@"userId":@"06",
@"name":@"wang",
@"nickName":@"wang66",
@"sex":@"1",
@"age":@"23",
@"mobile":@"wang",
@"email":@"wang@164.com"};
NSString *token = @"xxx";
[[UserModel shareInstance] handleAfterLoginSuccess:resultInfo token:token]; // 登录成功需要的处理