1、变更推送为阿里云推,清除云信IM以及推送内容;

2、消息页面全新改版;
3、部分微小Bug修复
This commit is contained in:
wbzhan
2019-05-24 19:21:31 +08:00
parent c586949438
commit 25c051d5f1
1544 changed files with 17136 additions and 78376 deletions
+25
View File
@@ -0,0 +1,25 @@
//
// AppDelegate+AliPushConfig.h
// Ifish
//
// Created by wbzhan on 2019/5/23.
// Copyright © 2019 lianlian. All rights reserved.
//
#import "AppDelegate.h"
#import<CloudPushSDK/CloudPushSDK.h>
// iOS 10 Notification
#import <UserNotifications/UserNotifications.h>
NS_ASSUME_NONNULL_BEGIN
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
#endif
@interface AppDelegate (AliPushConfig)<UNUserNotificationCenterDelegate>
// iOS 10 通知中心
@property (nonatomic, strong) UNUserNotificationCenter *notificationCenter;
//注册阿里推送
- (void)registerAliPush;
//注册苹果推送
- (void)registerAPNS:(UIApplication *)application;
@end
NS_ASSUME_NONNULL_END
+428
View File
@@ -0,0 +1,428 @@
//
// AppDelegate+AliPushConfig.m
// Ifish
//
// Created by wbzhan on 2019/5/23.
// Copyright © 2019 lianlian. All rights reserved.
//
#import "AppDelegate+AliPushConfig.h"
#import <objc/runtime.h>
static const void *NotificationCenterKey = &NotificationCenterKey;
@implementation AppDelegate (AliPushConfig)
- (UNUserNotificationCenter *)notificationCenter {
return objc_getAssociatedObject(self, NotificationCenterKey);
}
- (void)setNotificationCenter:(UNUserNotificationCenter *)notificationCenter {
objc_setAssociatedObject(self, NotificationCenterKey, notificationCenter, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
/**
* 向APNs注册,获取deviceToken 用于推送
* @param application
*/
- (void)registerAPNS:(UIApplication *)application {
float systemVersionNum = [[[UIDevice currentDevice] systemVersion] floatValue];
if (systemVersionNum >= 10.0) {
// iOS 10 notifications
self.notificationCenter = [UNUserNotificationCenter currentNotificationCenter];
// 创建 category,并注册到通知中心
[self createCustomNotificationCategory];
// 遵循协议
self.notificationCenter.delegate = self;
// 请求客户推送通知权限,以及推送的类型
[self.notificationCenter requestAuthorizationWithOptions:UNAuthorizationOptionAlert | UNAuthorizationOptionBadge | UNAuthorizationOptionSound completionHandler:^(BOOL granted, NSError * _Nullable error) {
if (granted) {
// granted
NSLog(@"\n ====== User authored notification.");
// 向APNs注册,获取deviceToken // 要求在主线程中
dispatch_async(dispatch_get_main_queue(), ^{
[application registerForRemoteNotifications];
});
} else {
// not granted
NSLog(@"\n ====== User denied notification.");
// 即使客户不允许通知也想让它通知 // 待测试
// 向APNs注册,获取deviceToken // 要求在主线程中
dispatch_async(dispatch_get_main_queue(), ^{
[application registerForRemoteNotifications];
});
}}];
/**
* 主动获取设备通知是否授权 (iOS 10+)
*/
[self.notificationCenter getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings * _Nonnull settings) {
// 进行判断做出相应的处理
if (settings.authorizationStatus == UNAuthorizationStatusNotDetermined) {
NSLog(@"\n ====== 未选择是否允许通知");
} else if (settings.authorizationStatus == UNAuthorizationStatusDenied) {
NSLog(@"\n ====== 未授权允许通知");
} else if (settings.authorizationStatus == UNAuthorizationStatusAuthorized){
NSLog(@"\n ====== 已授权允许通知");
}
}];
} else if (systemVersionNum >= 8.0) { // 适配 iOS_8, iOS_10.0
// iOS 8 Notifications
// 不会有黄色叹号
#pragma clang diagnostic push
#pragma clang diagnostic ignored"-Wdeprecated-declarations"
[application registerUserNotificationSettings:
[UIUserNotificationSettings settingsForTypes:
(UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge) categories:nil]];
[application registerForRemoteNotifications];
/*
// 提出弹窗,授权是否允许通知
UIUserNotificationSettings * settings = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeBadge|UIUserNotificationTypeSound|UIUserNotificationTypeAlert categories:nil];
[[UIApplication sharedApplication] registerUserNotificationSettings:settings];
// 注册远程通知 (iOS_8+)
[[UIApplication sharedApplication] registerForRemoteNotifications];
if ([[UIApplication sharedApplication] currentUserNotificationSettings].types == UIUserNotificationTypeNone) { //判断用户是否打开通知开关
NSLog(@"没有打开");
} else {
NSLog(@"已经打开");
}
*/
#pragma clang diagnostic pop
} else {
// iOS < 8 Notifications
#pragma clang diagnostic push
#pragma clang diagnostic ignored"-Wdeprecated-declarations"
[[UIApplication sharedApplication] registerForRemoteNotificationTypes:
(UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound)];
/*
UIRemoteNotificationType types = UIRemoteNotificationTypeBadge|UIRemoteNotificationTypeSound|UIRemoteNotificationTypeAlert;
[[UIApplication sharedApplication] registerForRemoteNotificationTypes:types];
if ([[UIApplication sharedApplication] enabledRemoteNotificationTypes] == UIRemoteNotificationTypeNone) { //判断用户是否打开通知开关
}
*/
#pragma clang diagnostic pop
}
}
/**
* 主动获取设备通知是否授权 (iOS 10+) 可以单独调用
*/
- (void)getNotificationSettingStatus {
[self.notificationCenter getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings * _Nonnull settings) {
if (settings.authorizationStatus == UNAuthorizationStatusAuthorized) {
NSLog(@"\n ====== 已经开启通知.");
} else {
NSLog(@"\n ====== 暂未开启通知.");
}}];
}
/**
* 创建并注册通知category (iOS 10+)
*/
- (void)createCustomNotificationCategory {
// 自定义 action1 和 action2
UNNotificationAction *action1 = [UNNotificationAction actionWithIdentifier:@"action1" title:@"test1" options: UNNotificationActionOptionNone];
UNNotificationAction *action2 = [UNNotificationAction actionWithIdentifier:@"action2" title:@"test2" options: UNNotificationActionOptionNone];
// 创建id为`test_category`的category,并注册两个action到category
// UNNotificationCategoryOptionCustomDismissAction 表明可以触发通知的 dismiss 回调
UNNotificationCategory *category = [UNNotificationCategory categoryWithIdentifier:@"test_category" actions:@[action1, action2] intentIdentifiers:@[] options: UNNotificationCategoryOptionCustomDismissAction];
// 注册category到通知中心
[self.notificationCenter setNotificationCategories:[NSSet setWithObjects:category, nil]];
}
/*
* APNs注册成功回调,将返回的deviceToken上传到CloudPush服务器
*/
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken NS_AVAILABLE_IOS(3_0) {
NSLog(@"Upload deviceToken to CloudPush server.");
//阿里推送注册成功回调
[CloudPushSDK registerDevice:deviceToken withCallback:^(CloudPushCallbackResult *res) {
if (res.success) {
NSString *userId = [dataContorl dataControlGetUserIdInfo];
NSString *device_Id = [CloudPushSDK getDeviceId];
NSLog(@"注册成功 device_token = %@",device_Id);
[FuncUserDefault setStr:device_Id key:kDeviceToken];//本机的devicetoken保存在本地
if (userId!=nil) {
NSDictionary *reqDic = @{
@"deviceId":device_Id,
@"userId":userId
};
[[AFNOHeaderHttpTool sharedInstance] postRequestWihtUrl:Push_BindDevice_Url params:reqDic success:^(NSDictionary *successDic) {
//绑定成功
[FuncUserDefault setBool:YES key:is_Bind_DeviceToken];
} failure:^(NSDictionary *errorDic) {
}];
}
} else {
NSLog(@"Register deviceToken failed, error: %@", res.error);
}
}];
}
/*
* APNs注册失败回调
*/
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
NSLog(@"\n ====== didFailToRegisterForRemoteNotificationsWithError %@", error);
}
#pragma mark SDK Init
- (void)registerAliPush {
// 正式上线关闭
[CloudPushSDK turnOnDebug];
// SDK初始化
[CloudPushSDK asyncInit:Ali_Push_APPKey appSecret:Ali_Push_APPSecret callback:^(CloudPushCallbackResult *res) {
if (res.success) {
NSLog(@"\n ====== 启动成功: %@.", [CloudPushSDK getDeviceId]);
} else {
NSLog(@"\n ====== 启动失败, error: %@", res.error);
}
}];
// 监听推送通道打开动作
[self listenerOnChannelOpened];
// 监听推送消息到达
[self registerMessageReceive];
// 主动获取设备通知是否授权 (iOS 10+)
[self getNotificationSettingStatus];
}
/**
* 注册推送通道 打开 监听
*/
- (void)listenerOnChannelOpened {
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(onChannelOpened:)
name:@"CCPDidChannelConnectedSuccess"
object:nil];
}
/**
* 推送通道打开回调
* @param notification
*/
- (void)onChannelOpened:(NSNotification *)notification {
NSLog(@"\n ====== 温馨提示,消息通道建立成功,该通道创建成功表示‘在线’,可以接收到推送的消息");
}
/**
* 注册推送消息 到来 监听
*/
- (void)registerMessageReceive {
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(onMessageReceived:)
name:@"CCPDidReceiveMessageNotification"
object:nil];
}
/**
* 处理到来推送消息
* @param notification
*/
- (void)onMessageReceived:(NSNotification *)notification {
//消息在通知栏显示,属于透传内容
NSLog(@"\n ====== Receive one message !!!!!!!");
CCPSysMessage *message = [notification object];
NSString *title = [[NSString alloc] initWithData:message.title encoding:NSUTF8StringEncoding];
NSString *body = [[NSString alloc] initWithData:message.body encoding:NSUTF8StringEncoding];
NSLog(@"\n ====== Receive message title: %@, content: %@.", title, body);
NSLog(@"\n ====== 当前线程 %@",[NSThread currentThread]);
[CommonUtils showAlerWithTitle:IsEmptyStr(title)?@"新消息":title withMsg:body];
}
#pragma mark —页面跳转(暂时不做处理)
- (void)jumpViewController:(NSDictionary *)tfdic {
// NSDictionary *remoteNotification = [tfdic objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
// for (NSString *tfStr in remoteNotification) {
// 通知里面的内容需要包含 " "
// if ([tfStr isEqualToString:@"careline"]) {
// JumpViewController *_viewController = [[JumpViewController alloc]init];
// UINavigationController *nav= (UINavigationController *)self.window.rootViewController;
// [nav pushViewController:_viewController animated:YES];
// }
// }
}
/**
* iOS 10 + 实现两个代理方法之一。
* 当APP处于后台 点击通知栏通知
* 触发通知动作时回调,比如点击、删除通知和点击自定义 action(iOS 10+)
*/
- (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)(void))completionHandler {
NSString *userAction = response.actionIdentifier;
// 点击通知打开app
if ([userAction isEqualToString:UNNotificationDefaultActionIdentifier]) {
NSLog(@"\n ====== User opened the notification.");
// 处理iOS 10通知,并上报通知打开回执
[self handleiOS10Notification:response.notification];
}
// 通知dismiss,category 创建时传入 UNNotificationCategoryOptionCustomDismissAction 才可以触发
if ([userAction isEqualToString:UNNotificationDismissActionIdentifier]) {
NSLog(@"\n ====== User dismissed the notification.");
}
// NSString *customAction1 = @"action1";
// NSString *customAction2 = @"action2";
//
// // 点击用户自定义Action1
// if ([userAction isEqualToString:customAction1]) {
// NSLog(@"User custom action1.");
// }
//
// // 点击用户自定义Action2
// if ([userAction isEqualToString:customAction2]) {
// NSLog(@"User custom action2.");
// }
completionHandler();
}
/**
* App 处于前台时收到通知 (iOS 10+ )
* iOS 10 + 实现两个代理方法之一。
* 只有当应用程序位于前台时,该方法才会在委托上调用。如果方法未被执行或处理程序没有及时调用,则通知将不会被提交。
* 应用程序可以选择将通知呈现为声音、徽章、警报和/或通知列表中。此决定应基于通知中的信息是否对用户可见。
*/
- (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler {
NSLog(@"\n ====== App 处于前台时收到通知 (iOS 10+ )");
// 处理iOS 10通知,并上报通知打开回执
[self handleiOS10Notification:notification];
/*
处理完成后调用 completionHandler ,用于指示在前台显示通知的形式
completionHandler() 功能:可设置是否在应用内弹出通知
在 iOS 10 中 通知在前台的显示设置:
*/
// 1、通知在前台不显示
// 如果调用下面代码: 通知不在前台弹出也不在通知栏显示
// completionHandler(UNNotificationPresentationOptionNone);
// 2、通知在前台显示
// 如果调用下面代码: 通知在前台弹出也在通知栏显示
// completionHandler(UNNotificationPresentationOptionAlert);
// 3、通知在前台显示 并带有声音
// 如果调用下面代码:通知弹出,且带有声音、内容和角标
// completionHandler(UNNotificationPresentationOptionSound | UNNotificationPresentationOptionAlert | UNNotificationPresentationOptionBadge);
completionHandler(UNNotificationPresentationOptionSound | UNNotificationPresentationOptionBadge);
}
/**
* 处理App 处于前台时收到通知 (iOS 10+ )
*/
- (void)handleiOS10Notification:(UNNotification *)notification {
UNNotificationRequest *request = notification.request;
UNNotificationContent *content = request.content;
NSDictionary *userInfo = content.userInfo;
// 通知时间
NSDate *noticeDate = notification.date;
// 标题
NSString *title = content.title;
// 副标题
NSString *subtitle = content.subtitle;
// 内容
NSString *body = content.body;
// 角标
int badge = [content.badge intValue];
// 取得通知自定义字段内容,例:获取key为"category"的内容
NSString *extras = [userInfo valueForKey:@"category"];
// 通知角标数清0
[UIApplication sharedApplication].applicationIconBadgeNumber = 0;
// 同步角标数到服务端
[self syncBadgeNum:0];
// 通知打开回执上报
[CloudPushSDK sendNotificationAck:userInfo];
NSLog(@"\n ====== App 处于前台时收到通知 (iOS 10+ ) Notification, == date: %@, == title: %@, == subtitle: %@, == body: %@, == badge: %d, == extras: %@.", noticeDate, title, subtitle, body, badge, extras);
[CommonUtils showAlerWithTitle:IsEmptyStr(title)?@"新通知":title withMsg:body];
}
/* 同步通知角标数到服务端 */
- (void)syncBadgeNum:(NSUInteger)badgeNum {
[CloudPushSDK syncBadgeNum:badgeNum withCallback:^(CloudPushCallbackResult *res) {
if (res.success) {
NSLog(@"\n ====== Sync badge num: [%lu] success.", (unsigned long)badgeNum);
} else {
NSLog(@"\n ====== Sync badge num: [%lu] failed, error: %@", (unsigned long)badgeNum, res.error);
}
}];
}
// iOS 7+ 不论是前台还是后台只要有远程推送都会调用
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult result))completionHandler NS_AVAILABLE_IOS(7_0) {
NSLog(@"\n ====== iOS 7+ 前台后台都会调用");
/*
建议使用该方法,还有一个作用。根据苹果给出的文档,系统给出30s的时间对推送的消息进行处理,此后就会运行CompletionHandler 程序块。
在处理这类推送消息(即程序被启动后接收到推送消息)的时候,通常会遇到这样的问题 :
就是当前的推送消息是当前程序正在前台运行时接收到的,还是说是程序在后台运行,用户点击系统消息通知栏对应项进入程序时而接收到的?这个其实很简单,用下面的代码就可以解决:
*/
// 做相应的判断是前台还是后台
if (application.applicationState == UIApplicationStateActive) {
// 程序当前正处于前台 如果不做处理里面不用写 就可以了
/*
关于userInfo的结构,参照苹果的官方结构:
{
"aps" : {
"alert" : "You got your emails.",
"badge" : 9,
"sound" : "bingbong.aiff"
"acme1" : "bar",
"acme2" : 42
}
即key aps 对应了有一个字典,里面是该次推送消息的具体信息。具体跟我们注册的推送类型有关。另外剩下的一些key就是用户自定义的了。
*/
} else if (application.applicationState == UIApplicationStateInactive) {
// // 程序处于后台 做相应的处理
// for (NSString *tfStr in userInfo) {
// if ([tfStr isEqualToString:@"careline"]) {
// JumpViewController *_viewController = [[JumpViewController alloc]init];
// UINavigationController *nav= (UINavigationController *)self.window.rootViewController;
// [nav pushViewController:_viewController animated:YES];
// }
// }
}
}
@end
+156
View File
@@ -0,0 +1,156 @@
//
// CommonUtils.h
// TTJF
//
// Created by 土土金服ios-01 on 2018/3/9.
// Copyright © 2018年 TTJF. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "UIColor+HexString.h"
@interface CommonUtils : NSObject
typedef enum{
DirectionFromLeft,//渐变色方向
DirectionFromTop
}GradientDirectionType;
//分割线颜色
#define HEXCOLOR(c) [UIColor colorWithHexString:c]
#define separaterColor HEXCOLOR(@"#e5e5e5")
//系统默认整体页面背景色
#define COLOR_Background HEXCOLOR(@"#f6f6f6")
/**
获取手机型号
*/
+(NSString*)getPhoneModel;
/**
获取手机UUID
*/
+(NSString *)getUUID;
/**
获取手机deviceToken
*/
+(NSString *)getDeviceToken;
/**
获取当前时间戳
*/
+(NSString *)getCurrentTimestamp;
//上送token(非用户唯一标示,为校验码)
+(NSString *)getToken;
+(NSString *)getUsername;
+(NSString *)getNikename;
//获取版本号
+(NSString *)getVersion;
//判断是否登录
+(BOOL)isLogin;
//是否已经托管到汇付
+(BOOL)isTrustReg;
//是否实名认证过
+(BOOL)isVerifyRealName;
//是否需要版本升级
+(BOOL)isUpdate;
//判断中英混合的的字符串长度
+ (int)convertToInt:(NSString*)strtemp;
//校验字符串是否含空格
+ (BOOL)checkEmptyString:(NSString *)string ;
//校验是否是数字
+(BOOL)isNumber:(NSString *)str;
//******************************输入内容正确性校验*****************************************//
#pragma 正则匹配手机号
+ (BOOL)checkTelNumber:(NSString *) telNumber;
#pragma 正则匹配用户密码6-18位数字和字母组合
+ (BOOL)checkPassword:(NSString *) password;
#pragma 正则匹配用户姓名,20位的中文或英文
+ (BOOL)checkUserName : (NSString *) userName;
#pragma 正则匹配用户身份证号
+ (BOOL)checkUserIdCard: (NSString *) idCard;
#pragma 正则匹配URL
+ (BOOL)checkURL : (NSString *) url;
///*******************缓存处理***********************************************/
//加入缓存
+ (void)SetCacheDataWithObject:(NSDictionary *)object WithPathName:(NSString *)withPathName;
//通过key值取得缓存数据
+(NSDictionary *)getCacheDataWithKey:(NSString *)cacheKey;
//移除特定缓存
+(void)removeCacheWithKey:(NSString *)cacheKey;
//移除所有缓存内容
+(void)removeAllCache;
//判断是否有缓存
+(BOOL)isContainCache:(NSString *)cacheKey;
/*******************常用方法***********************************************/
/**
获取千分位的数字
*/
+(NSString *)getHanleNums:(NSString *)numbers;
/**
获取字符串中的数字内容
*/
+(NSString *)getNumberFromString:(NSString *)str;
/**
数组转jsonString
*/
+ (NSString *)arrayToJSONString:(NSArray *)array;
/**
获取根视图控制器
*/
+ (UIViewController *)appRootViewController;
/**
系统自带提示框显示
*/
+(void)showAlerWithTitle:(NSString*)title withMsg:(NSString*)msg;
/**
获取当前时间戳
@return nil
*/
+(NSString *)getNowTimeTimestamp;
/*!
* 获取时间差
*
* @param fromdate 起始时间
* @param todate 结束时间
*
* @return 时间差(秒)
*/
+ (int)getSecondForFromDate:(NSDate *)fromdate toDate:(NSDate *)todate;
/*!
* 获取给定时间到当前时间的时间差
* @return 时间差(秒)
*/
+ (NSInteger)getDifferenceByDate:(NSString *)creat_time;
/**
获取倒计时显示字符串
*/
+(NSString *)getCountDownTime:(NSInteger)timeInval;
/**
带有行间距的label的高度
*/
+(CGFloat)getSpaceLabelHeight:(NSString*)str withFont:(UIFont*)font withWidth:(CGFloat)width lineSpace:(CGFloat)lineSpace;
/**设置带圆角带阴影*/
+(void)setShadowCornerRadiusToView:(UIView *)view;
//给view添加渐变色
+(void)addGradientLayer:(UIView *)view startColor:(UIColor *)startColor endColor:(UIColor *)endColor withDirection:(GradientDirectionType)direction;
/**
设置带有行间距的label
*/
+(void)setAttString:(NSString *)title withLineSpace:(CGFloat)space titleLabel:(UILabel *) titleLabel;
/**
设置字符串的字体大小和颜色
@param string 当前处理的可变字符串
@param range range
@param font 字体大小
@param color 颜色
*/
+ (NSMutableAttributedString *)diffierentFontWithString:(NSString *)string rang:(NSRange)range font:(UIFont *)font color:(UIColor *)color spacingBeforeValue:(CGFloat)spacingBeforeValue lineSpace:(CGFloat)lineSpace;
/**
获取随机数
*/
+ (NSString *)getRandomStringWithNum:(NSInteger)num;
CGAffineTransform GetCGAffineTransformRotateAroundPoint(float centerX, float centerY ,float x ,float y ,float angle);
@end
+688
View File
@@ -0,0 +1,688 @@
//
// CommonUtils.m
// AS
//
// Created by 土土金服ios-01 on 2018/3/9.
// Copyright © 2018年 AS. All rights reserved.
//
#import "CommonUtils.h"
#import "YYCache.h"
#import <sys/utsname.h>
@implementation CommonUtils
//******************************输入内容正确性校验*****************************************//
#pragma 正则匹配用户密码6-15位数字和字母和符号的组合
+ (BOOL)checkPassword:(NSString *) password
{
NSString *pattern = @"^(?![0-9]+$)(?![a-zA-Z]+$)[a-zA-Z0-9]{6,15}";
NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", pattern];
BOOL isMatch = [pred evaluateWithObject:password];
return isMatch;
}
#pragma 正则匹配用户姓名,8位的中文或英文或数字
+ (BOOL)checkUserName : (NSString *) userName
{
// NSString *pattern = @"^[\u4e00-\u9fa5]{1,8}$|^[0-9A-Za-z]{1,16}$";
NSString *pattern = @"^[0-9a-zA-Z\u4E00-\u9FA5]{1,8}";
NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", pattern];
BOOL isMatch = [pred evaluateWithObject:userName];
return isMatch;
}
#pragma 正则匹配用户身份证号15或18位
+ (BOOL)checkUserIdCard: (NSString *) userID
{
//长度不为18的都排除掉
if (userID.length!=18) {
return NO;
}
//校验格式
NSString *regex2 = @"^(^[1-9]\\d{7}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}$)|(^[1-9]\\d{5}[1-9]\\d{3}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])((\\d{4})|\\d{3}[Xx])$)$";
NSPredicate *identityCardPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex2];
BOOL flag = [identityCardPredicate evaluateWithObject:userID];
if (!flag) {
return flag; //格式错误
}else {
//格式正确在判断是否合法
//将前17位加权因子保存在数组里
NSArray * idCardWiArray = @[@"7", @"9", @"10", @"5", @"8", @"4", @"2", @"1", @"6", @"3", @"7", @"9", @"10", @"5", @"8", @"4", @"2"];
//这是除以11后,可能产生的11位余数、验证码,也保存成数组
NSArray * idCardYArray = @[@"1", @"0", @"10", @"9", @"8", @"7", @"6", @"5", @"4", @"3", @"2"];
//用来保存前17位各自乖以加权因子后的总和
NSInteger idCardWiSum = 0;
for(int i = 0;i < 17;i++)
{
NSInteger subStrIndex = [[userID substringWithRange:NSMakeRange(i, 1)] integerValue];
NSInteger idCardWiIndex = [[idCardWiArray objectAtIndex:i] integerValue];
idCardWiSum+= subStrIndex * idCardWiIndex;
}
//计算出校验码所在数组的位置
NSInteger idCardMod=idCardWiSum%11;
//得到最后一位身份证号码
NSString * idCardLast= [userID substringWithRange:NSMakeRange(17, 1)];
//如果等于2,则说明校验码是10,身份证号码最后一位应该是X
if(idCardMod==2)
{
if([idCardLast isEqualToString:@"X"]||[idCardLast isEqualToString:@"x"])
{
return YES;
}else
{
return NO;
}
}else{
//用计算出的验证码与最后一位身份证号码匹配,如果一致,说明通过,否则是无效的身份证号码
if([idCardLast isEqualToString: [idCardYArray objectAtIndex:idCardMod]])
{
return YES;
}
else
{
return NO;
}
}
}
// NSString *pattern = @"(^[0-9]{15}$)|([0-9]{17}([0-9]|X)$)";
// NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", pattern];
// BOOL isMatch = [pred evaluateWithObject:idCard];
// return isMatch;
}
#pragma 正则匹配URL
+ (BOOL)checkURL : (NSString *) url
{
NSString *pattern = @"^[0-9A-Za-z]{1,50}";
NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", pattern];
BOOL isMatch = [pred evaluateWithObject:url];
return isMatch;
}
//手机号识别
+ (BOOL)checkTelNumber:(NSString *)telNumber{
if (telNumber.length != 11)
{
return NO;
}
/**
* 手机号码:
* 13[0-9], 14[5,7], 15[0, 1, 2, 3, 5, 6, 7, 8, 9], 17[6, 7, 8], 18[0-9], 170[0-9]
* 移动号段: 134,135,136,137,138,139,150,151,152,157,158,159,182,183,184,187,188,147,178,1705
* 联通号段: 130,131,132,155,156,185,186,145,176,1709
* 电信号段: 133,153,180,181,189,177,1700
*/
NSString *MOBILE = @"^1(3[0-9]|4[0-9]|5[0-9]|6[0-9]|7[0-9]|8[0-9]|9[0-9])\\d{8}$";
NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBILE];
if ([regextestmobile evaluateWithObject:telNumber] == YES)
{
return YES;
}
else
{
return NO;
}
}
/**
获取字符串中的数字内容
*/
+(NSString *)getNumberFromString:(NSString *)str{
NSScanner *scanner = [NSScanner scannerWithString:str];
[scanner scanUpToCharactersFromSet:[NSCharacterSet decimalDigitCharacterSet] intoString:nil];
float number;
[scanner scanFloat:&number];
NSString *num=[NSString stringWithFormat:@"%.2f",number];
return num;
}
+(BOOL)isNumber:(NSString *)str {
str = [str stringByTrimmingCharactersInSet:[NSCharacterSet decimalDigitCharacterSet]];
if (str.length>0) {
//带小数点的数字
if ([str isEqualToString:@"."]) {
return YES;
}else
return NO;
}
return YES;
}
//*******************缓存处理***********************************************/
/**
加入缓存
*/
+ (void)SetCacheDataWithObject:(NSDictionary *)object WithPathName:(NSString *)withPathName{
YYCache *yyCache=[YYCache cacheWithName:@"IfishCache"];
//根据key写入缓存value
[yyCache setObject:object forKey:withPathName];
}
/**
通过key值取得缓存数据
*/
+(NSDictionary *)getCacheDataWithKey:(NSString *)cacheKey{
YYCache *yyCache=[YYCache cacheWithName:@"IfishCache"];
return (NSDictionary *)[yyCache objectForKey:cacheKey];
}
/**
移除特定缓存
*/
+(void)removeCacheWithKey:(NSString *)cacheKey{
YYCache *yyCache=[YYCache cacheWithName:@"IfishCache"];
[yyCache removeObjectForKey:cacheKey];
}
+(BOOL)isContainCache:(NSString *)cacheKey{
YYCache *yyCache=[YYCache cacheWithName:@"IfishCache"];
return [yyCache containsObjectForKey:cacheKey];
}
/**
移除所有缓存
*/
+(void)removeAllCache{
YYCache *yyCache=[YYCache cacheWithName:@"IfishCache"];
[yyCache removeAllObjects];
}
//移除所有缓存内容
//**************************获取当前版本号*********************************************//
+(NSString *)getVersion{
NSString *version = [FuncUserDefault strForKey:BundleVersion];
if (IsEmptyStr(version)) {
return @"";
}else{
return version;
}
}
+(NSString *)getUUID{
NSString *uuid = [FuncUserDefault strForKey:@"AS_uuid"];
if (uuid==nil) {
uuid = [[[UIDevice currentDevice] identifierForVendor] UUIDString];
[FuncUserDefault setStr:uuid key:@"AS_uuid"];
return uuid;
}else
return [FuncUserDefault strForKey:@"AS_uuid"];
}
//获取手机型号
+(NSString*)getPhoneModel
{
struct utsname systemInfo;
uname(&systemInfo);
NSString * phoneType = [NSString stringWithCString:systemInfo.machine encoding:NSUTF8StringEncoding];
//iPhone
if([phoneType isEqualToString:@"iPhone4,1"]) return@"iPhone 4S";
if([phoneType isEqualToString:@"iPhone5,1"]) return@"iPhone 5";
if([phoneType isEqualToString:@"iPhone5,2"]) return@"iPhone 5";
if([phoneType isEqualToString:@"iPhone5,3"]) return@"iPhone 5c";
if([phoneType isEqualToString:@"iPhone5,4"]) return@"iPhone 5c";
if([phoneType isEqualToString:@"iPhone6,1"]) return@"iPhone 5s";
if([phoneType isEqualToString:@"iPhone6,2"]) return@"iPhone 5s";
if([phoneType isEqualToString:@"iPhone7,1"]) return@"iPhone 6 Plus";
if([phoneType isEqualToString:@"iPhone7,2"]) return@"iPhone 6";
if([phoneType isEqualToString:@"iPhone8,1"]) return@"iPhone 6s";
if([phoneType isEqualToString:@"iPhone8,2"]) return@"iPhone 6s Plus";
if([phoneType isEqualToString:@"iPhone8,4"]) return@"iPhone SE";
if([phoneType isEqualToString:@"iPhone9,1"]) return@"iPhone 7";
if([phoneType isEqualToString:@"iPhone9,2"]) return@"iPhone 7 Plus";
if([phoneType isEqualToString:@"iPhone10,1"]) return@"iPhone 8";
if([phoneType isEqualToString:@"iPhone10,4"]) return@"iPhone 8";
if([phoneType isEqualToString:@"iPhone10,2"]) return@"iPhone 8 Plus";
if([phoneType isEqualToString:@"iPhone10,5"]) return@"iPhone 8 Plus";
if([phoneType isEqualToString:@"iPhone10,3"]) return@"iPhone X";
if([phoneType isEqualToString:@"iPhone10,6"]) return@"iPhone X";
return @"iPhone";
}
/**
获取当前时间戳
*/
+(NSString *)getCurrentTimestamp{
NSDate* date = [NSDate dateWithTimeIntervalSinceNow:0];//获取当前时间0秒后的时间
NSTimeInterval time=[date timeIntervalSince1970];// *1000 是精确到毫秒,不乘就是精确到秒
NSString *timeString = [NSString stringWithFormat:@"%.0f", time];
return timeString;
}
//view围绕任意一点旋转
CGAffineTransform GetCGAffineTransformRotateAroundPoint(float centerX, float centerY ,float x ,float y ,float angle)
{
x = x - centerX; //计算(x,y)从(0,0)为原点的坐标系变换到(CenterX ,CenterY)为原点的坐标系下的坐标
y = y - centerY; //(0,0)坐标系的右横轴、下竖轴是正轴,(CenterX,CenterY)坐标系的正轴也一样
CGAffineTransform trans = CGAffineTransformMakeTranslation(x, y);
trans = CGAffineTransformRotate(trans,angle);
trans = CGAffineTransformTranslate(trans,-x, -y);
return trans;
}
//**************************获取token*********************************************//
+(NSString *)getToken{
NSString *token = [FuncUserDefault strForKey:kToken];
if (IsEmptyStr(token)) {
return @"";
}else{
return token;
}
}
+(NSString *)getDeviceToken{
NSString *token = [FuncUserDefault strForKey:kDeviceToken];
if (IsEmptyStr(token)) {
return [self getUUID];
}else{
return token;
}
}
//**************************获取userName*********************************************//
+(NSString *)getUsername{
NSString *username = [FuncUserDefault strForKey:kUsername];
if (IsEmptyStr(username)) {
return @"";
}else{
return username;
}
}
/**获取昵称*/
+(NSString *)getNikename
{
NSString *nikename = [FuncUserDefault strForKey:kNikename];
if (IsEmptyStr(nikename)) {
return @"";
}else{
return nikename;
}
}
//是否登录
+(BOOL)isLogin
{
NSString *token = [FuncUserDefault strForKey:kToken];
if (!IsEmptyStr(token)) {
return YES;
}else
return NO;
}
//是否需要版本升级
+(BOOL)isUpdate{
NSString *version = [FuncUserDefault strForKey:BundleVersion];
if (IsEmptyStr(version)) {
return NO;
}else{
if ([version isEqualToString:Version_Code]) {
return NO;
}else{
return YES;
}
}
}
/**
是否已经托管到汇付
*/
+(BOOL)isTrustReg{
NSString *str = @"";
if (IsEmptyStr(str)||[str isEqualToString:@"-1"]) {
return NO;
}else
return YES;
}
/**
是否实名认证过
*/
+(BOOL)isVerifyRealName{
// NSString *str = [FuncUserDefault strForKey:isCertificationed];
// if (IsEmptyStr(str)||[str isEqualToString:@"-1"]) {
// return NO;
// }else
return YES;
}
/*! 获取时间差(秒) */
+ (int)getSecondForFromDate:(NSDate *)fromdate toDate:(NSDate *)todate {
NSTimeInterval fromInt = [fromdate timeIntervalSince1970]; // 获取离1970年间隔
NSTimeInterval toInt = [todate timeIntervalSince1970];
NSTimeInterval interval = toInt - fromInt; // 获取时间差值
return interval*1;
}
//获取时间差(48小时内需要倒计时显示)
+ (NSInteger)getDifferenceByDate:(NSString *)creat_time {
if (IsEmptyStr(creat_time)) {
return 0;
}
NSDate *nowDate = [NSDate date]; // 当前时间
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = @"yyyy-MM-dd HH-mm-ss";
NSDate *creat = [formatter dateFromString:creat_time]; // 传入的时间
NSTimeInterval timeInterval = [creat timeIntervalSinceDate:nowDate];
if (timeInterval<=0) {
return 0;
}else{
return [[NSString stringWithFormat:@"%.0f",timeInterval] integerValue];
}
// NSCalendar *calendar = [NSCalendar currentCalendar];
// NSCalendarUnit unit = NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
// NSDateComponents *compas = [calendar components:unit fromDate:nowDate toDate:creat options:0];
//
//
// NSInteger day= [compas day];
// NSInteger mounth = [compas month];
// NSInteger year = [compas year];
// NSInteger hour = [compas hour];
// NSInteger minute = [compas minute];
// NSInteger second = [compas second];
// if(day<0)
// return 0;
// NSInteger sss= [compas second]+compas.hour*HOUR+[compas minute]*MINUTE+day*DAY;
// if(sss<0)
// return 0;
// return sss;
}
//获取当前时间戳
+(NSString *)getNowTimeTimestamp{
NSDateFormatter *formatter = [[NSDateFormatter alloc] init] ;
[formatter setDateStyle:NSDateFormatterMediumStyle];
[formatter setTimeStyle:NSDateFormatterShortStyle];
[formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"]; // ----------设置你想要的格式,hh与HH的区别:分别表示12小时制,24小时制
//设置时区,这个对于时间的处理有时很重要
NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"Asia/Shanghai"];
[formatter setTimeZone:timeZone];
NSDate *datenow = [NSDate date];//现在时间,你可以输出来看下是什么格式
NSString *timeSp = [NSString stringWithFormat:@"%ld", (long)[datenow timeIntervalSince1970]];
return timeSp;
}
//获取倒计时字符串
+(NSString *)getCountDownTime:(NSInteger)timeInval
{
NSInteger hour=timeInval/HOUR;
NSInteger day=(hour-(hour%24))/24;
NSString *str_day = [NSString stringWithFormat:@"%ld",day];
NSString *str_hour = [NSString stringWithFormat:@"%ld",hour%24];
NSString *str_minute = [NSString stringWithFormat:@"%ld",(timeInval%HOUR)/MINUTE];
NSString *str_second = [NSString stringWithFormat:@"%ld",timeInval%MINUTE];
//修改倒计时标签现实内容
NSString * countDown=[NSString stringWithFormat:@"%@天%@时%@分%@秒",str_day,str_hour,str_minute, str_second];
if ([[countDown substringToIndex:2] isEqualToString:@"0天"]) {
countDown = [countDown stringByReplacingOccurrencesOfString:@"0天" withString:@""];
}
if ([[countDown substringToIndex:2] isEqualToString:@"0时"]) {
countDown = [countDown stringByReplacingOccurrencesOfString:@"0时" withString:@""];
}
if ([[countDown substringToIndex:2] isEqualToString:@"0分"]) {
countDown = [countDown stringByReplacingOccurrencesOfString:@"0分" withString:@""];
}
return countDown;
}
+ (int)convertToInt:(NSString*)strtemp//判断中英混合的的字符串长度
{
int strlength = 0;
char* p = (char*)[strtemp cStringUsingEncoding:NSUnicodeStringEncoding];
for (int i=0 ; i<[strtemp lengthOfBytesUsingEncoding:NSUnicodeStringEncoding] ;i++) {
if (*p) {
p++;
strlength++;
}
else {
p++;
}
}
return strlength;
}
//判断字符串中是否包含空格
+ (BOOL)checkEmptyString:(NSString *)string {
NSRange range = [string rangeOfString:@" "];
if (range.location != NSNotFound) {
return YES;
}
return NO;
}
//判断是否为空或全为空格
+ (BOOL)isEmptyWithString:(NSString *)str {
if (str == nil) {
return YES;
} else if (!str.length) {
return YES;
} else {
NSCharacterSet *set = [NSCharacterSet whitespaceAndNewlineCharacterSet];
NSString *string = [str stringByTrimmingCharactersInSet:set];
if (string.length == 0) {
return YES;
} else {
return NO;
}
}
}
+ (NSString *)arrayToJSONString:(NSArray *)array
{
NSError *error = nil;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:array
options:kNilOptions
error:&error];
NSString *jsonString = [[NSString alloc] initWithData:jsonData
encoding:NSUTF8StringEncoding];
return jsonString;
}
+ (UIViewController *)appRootViewController
{
UIViewController *appRootVC = [UIApplication sharedApplication].keyWindow.rootViewController;
UIViewController *topVC = appRootVC;
while (topVC.presentedViewController) {
topVC = topVC.presentedViewController;
}
return topVC;
}
+(void)showAlerWithTitle:(NSString*)title withMsg:(NSString*)msg{
[self showAlertControllerWithTitle:title withMsg:msg target:[self appRootViewController]];
}
+(void)showAlertControllerWithTitle:(NSString*)title withMsg:(NSString*)msg target:(id)target{
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:title message:msg preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *alertAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
[alertController addAction:alertAction];
[target presentViewController:alertController animated:YES completion:nil];
}
/**
获取千分位的数字字符串
*/
+(NSString *)getHanleNums:(NSString *)numbers{
NSString *resault ;
if ([numbers isEqualToString:@"-"]) {
return resault;
}
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
formatter.numberStyle = kCFNumberFormatterDecimalStyle;
if ([numbers rangeOfString:@"."].location!=NSNotFound) {
[formatter setPositiveFormat:@"###,##0.00"];//千分位格式
}else
[formatter setPositiveFormat:@"###,##0"];//千分位格式,带小数点
resault = [formatter stringFromNumber:[NSNumber numberWithDouble:[numbers doubleValue]]];//此处使用doublevale,防止失真
return resault;
}
//动态获取label高度
+(CGFloat)getSpaceLabelHeight:(NSString*)str withFont:(UIFont*)font withWidth:(CGFloat)width lineSpace:(CGFloat)lineSpace{
NSMutableParagraphStyle *paraStyle = [[NSMutableParagraphStyle alloc] init];
paraStyle.lineBreakMode = NSLineBreakByCharWrapping;
paraStyle.alignment = NSTextAlignmentLeft;
//获得带有行间距为2的高度
paraStyle.lineSpacing = lineSpace;
paraStyle.hyphenationFactor = 1.0;
paraStyle.firstLineHeadIndent = 0.0;
paraStyle.paragraphSpacingBefore = 0.0;
paraStyle.headIndent = 0;
paraStyle.tailIndent = 0;
//字间距为0
NSDictionary *dic = @{NSFontAttributeName:font, NSParagraphStyleAttributeName:paraStyle, NSKernAttributeName:@0.f
};
CGSize size = [str boundingRectWithSize:CGSizeMake(width, 999.f) options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading|NSStringDrawingTruncatesLastVisibleLine attributes:dic context:nil].size;
return size.height ;
}
/**
设置带有行间距的内容
*/
+(void)setAttString:(NSString *)title withLineSpace:(CGFloat)space titleLabel:(UILabel *) titleLabel
{
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:title];
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
[paragraphStyle setLineSpacing:space];
[attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [title length])];
titleLabel.attributedText = attributedString;
}
//设置带圆角带阴影
+(void)setShadowCornerRadiusToView:(UIView *)view{
view.layer.cornerRadius = kSizeFrom750(10);
view.layer.shadowColor = [UIColor grayColor].CGColor;
view.layer.shadowOffset = CGSizeMake(0, kSizeFrom750(10));
view.layer.shadowOpacity = 0.2;
view.layer.shadowRadius = kSizeFrom750(8);
}
//给view添加渐变色
+(void)addGradientLayer:(UIView *)view startColor:(UIColor *)startColor endColor:(UIColor *)endColor withDirection:(GradientDirectionType)direction
{
CAGradientLayer *gradientLayer = [CAGradientLayer layer];
gradientLayer.colors = @[(__bridge id)startColor.CGColor, (__bridge id)endColor.CGColor];
if (direction==DirectionFromTop) {//从上到下
gradientLayer.startPoint = CGPointMake(0.5, 0);//绘图起始点(x/Y)//顶部中间位置
gradientLayer.locations = @[@(0.5),@(1.0)];
gradientLayer.endPoint = CGPointMake(0.5, 1.0);
}else{
gradientLayer.startPoint = CGPointMake(0, 0.5);//绘图起始点(x/Y)//左边距中间位置
gradientLayer.locations = @[@(0.5),@(1.0)];
gradientLayer.endPoint = CGPointMake(1.0, 0.5);
}
gradientLayer.frame = view.bounds;
[view.layer addSublayer:gradientLayer];
}
/**
设置字符串的字体大小和颜色
@param string 当前处理的可变字符串
@param range range
@param fontValue 字体
@param colorString 颜色
@param spacingBeforeValue 首行缩进
@return
*/
+ (NSMutableAttributedString *)diffierentFontWithString:(NSString *)string rang:(NSRange)range font:(UIFont *)font color:(UIColor *)color spacingBeforeValue:(CGFloat)spacingBeforeValue lineSpace:(CGFloat)lineSpace{
if (IsEmptyStr(string)) {
return [NSMutableAttributedString new];
}
NSMutableAttributedString *attributeString = [[NSMutableAttributedString alloc] initWithString:string];
if (string.length) {
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
[paragraphStyle setLineSpacing:lineSpace];
paragraphStyle.hyphenationFactor = 1.0;
paragraphStyle.firstLineHeadIndent = 0.0;
paragraphStyle.paragraphSpacingBefore = spacingBeforeValue;
paragraphStyle.headIndent = 0;
paragraphStyle.tailIndent = 0;
paragraphStyle.alignment = NSTextAlignmentCenter;
[attributeString addAttributes:@{NSFontAttributeName:font, NSParagraphStyleAttributeName:paragraphStyle} range:range];
if (color!=nil) {
[attributeString addAttribute:NSForegroundColorAttributeName value:color range:range];
}
}
return attributeString;
}
//获取随机数
+ (NSString *)getRandomStringWithNum:(NSInteger)num
{
NSString *string = [[NSString alloc]init];
for (int i = 0; i < num; i++) {
int number = arc4random() % 36;
if (number < 10) {
int figure = arc4random() % 10;
NSString *tempString = [NSString stringWithFormat:@"%d", figure];
string = [string stringByAppendingString:tempString];
}else {
int figure = (arc4random() % 26) + 97;
char character = figure;
NSString *tempString = [NSString stringWithFormat:@"%c", character];
string = [string stringByAppendingString:tempString];
}
}
return string;
}
@end
+94
View File
@@ -0,0 +1,94 @@
//
// TTJFUserDefault.h
// TTJF
//
// Created by 土土金服ios-01 on 2018/3/8.
// Copyright © 2018年 TTJF. All rights reserved.
//小数据持久化存储
#import <Foundation/Foundation.h>
@interface FuncUserDefault : NSObject
/**
* 保存普通字符串
*/
+(void)setStr:(NSString *)str key:(NSString *)key;
/**
* 读取
*/
+(NSString *)strForKey:(NSString *)key;
/**
* 删除
*/
+(void)removeStrForKey:(NSString *)key;
/**
* 保存普通数组
*/
+(void)setArr:(NSArray *)arr key:(NSString *)key;
/**
* 读取数组
*/
+(NSArray *)arrForKey:(NSString *)key;
/**
* 删除数组
*/
+(void)removeArrForKey:(NSString *)key;
/**
* 保存int
*/
+(void)setInt:(NSInteger)i key:(NSString *)key;
/**
* 读取int
*/
+(NSInteger)intForKey:(NSString *)key;
/**
* 保存float
*/
+(void)setFloat:(CGFloat)floatValue key:(NSString *)key;
/**
* 读取float
*/
+(CGFloat)floatForKey:(NSString *)key;
/**
* 保存bool
*/
+(void)setBool:(BOOL)boolValue key:(NSString *)key;
/**
* 读取bool
*/
+(BOOL)boolForKey:(NSString *)key;
#pragma mark - 文件归档
/**
* 归档
*/
+(BOOL)archiveRootObject:(id)obj toFile:(NSString *)path;
/**
* 删除
*/
+(BOOL)removeRootObjectWithFile:(NSString *)path;
/**
* 解档
*/
+(id)unarchiveObjectWithFile:(NSString *)path;
@end
+173
View File
@@ -0,0 +1,173 @@
//
// TTJFUserDefault.m
// TTJF
//
// Created by 土土金服ios-01 on 2018/3/8.
// Copyright © 2018年 TTJF. All rights reserved.
//
#import "FuncUserDefault.h"
@implementation FuncUserDefault
#pragma mark - 偏好类信息存储
//保存普通对象
+(void)setStr:(NSString *)str key:(NSString *)key{
//获取preference
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
//保存
[defaults setObject:str forKey:key];
//立即同步
[defaults synchronize];
}
//读取
+(NSString *)strForKey:(NSString *)key{
//获取preference
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
//读取
NSString *str=(NSString *)[defaults objectForKey:key];
return str;
}
//删除
+(void)removeStrForKey:(NSString *)key{
//获取preference
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:@"" forKey:key];
//立即同步
[defaults synchronize];
}
#pragma mark --保存数组
+(void)setArr:(NSArray *)arr key:(NSString *)key{
//获取preference
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
//保存
[defaults setObject:arr forKey:key];
//立即同步
[defaults synchronize];
}
//读取数组
+(NSArray *)arrForKey:(NSString *)key{
//获取preference
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
//读取
NSArray *arr=(NSArray *)[defaults objectForKey:key];
return arr;
}
//删除数组
+(void)removeArrForKey:(NSString *)key{
[self setArr:nil key:key];
[[NSUserDefaults standardUserDefaults] removeObjectForKey:key];
}
//保存int
+(void)setInt:(NSInteger)i key:(NSString *)key{
//获取preference
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
//保存
[defaults setInteger:i forKey:key];
//立即同步
[defaults synchronize];
}
//读取
+(NSInteger)intForKey:(NSString *)key{
//获取preference
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
//读取
NSInteger i=[defaults integerForKey:key];
return i;
}
//保存float
+(void)setFloat:(CGFloat)floatValue key:(NSString *)key{
//获取preference
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
//保存
[defaults setFloat:floatValue forKey:key];
//立即同步
[defaults synchronize];
}
//读取
+(CGFloat)floatForKey:(NSString *)key{
//获取preference
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
//读取
CGFloat floatValue=[defaults floatForKey:key];
return floatValue;
}
//保存bool
+(void)setBool:(BOOL)boolValue key:(NSString *)key{
//获取preference
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
//保存
[defaults setBool:boolValue forKey:key];
//立即同步
[defaults synchronize];
}
//读取
+(BOOL)boolForKey:(NSString *)key{
//获取preference
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
//读取
BOOL boolValue=[defaults boolForKey:key];
return boolValue;
}
#pragma mark - 文件归档
//归档
+(BOOL)archiveRootObject:(id)obj toFile:(NSString *)path{
return [NSKeyedArchiver archiveRootObject:obj toFile:path];
}
//删除
+(BOOL)removeRootObjectWithFile:(NSString *)path{
return [self archiveRootObject:nil toFile:path];
}
//解档
+(id)unarchiveObjectWithFile:(NSString *)path{
return [NSKeyedUnarchiver unarchiveObjectWithFile:path];
}
@end