1:配置网络环境
2.创建一个.pch文件
3.倒入第三方:
‘AFNetworking’, ‘~> 3.0’
QMUIKit,
Masonry,
SDCycleScrollView
MJRefresh 等
4.创建一个baseVC
5.创建一个继承UINavigationController的VC
6.创建一个继承UITabBarController的VC
7.创建一个网络请求的类
8.创建一个基础工具
//*********************** 配置网络环境****************
1.在plist文件里面添加:key:App Transport Security Settings 设置为dictionary类型
2. 在App Transport Security Settings 字典里添加key :Allow Arbitrary Loads 设置为YES
//*********************** 创建一个.pch文件****************
这篇文章有介绍:https://editor.csdn.net/md/?articleId=78491756
//*********************** 倒入第三方****************
1.例:
platform :ios, ‘8.0’
use_frameworks!
target ‘yoga’ do
pod “GCWebviewJSBridge”
pod ‘QMUIKit’
pod ‘YBPopupMenu’, ‘~> 1.1.2’
pod ‘Masonry’
pod ‘SDCycleScrollView’,’~> 1.64’
pod ‘AFNetworking’, ‘~> 3.0’
pod ‘MinScrollMenu’
pod ‘WXWaveView’
pod ‘JSONModel’
pod ‘BRPickerView’ , ‘~> 1.0.0’
pod ‘MJRefresh’
pod ‘ZXScrollPageView’
pod “PYSearch”
pod ‘ScottAlertController’
pod ‘IQKeyboardManager’
pod ‘XHLaunchAd’
pod ‘ICPagingManager’
pod ‘MJExtension’
pod ‘HXWeiboPhotoPicker’, ‘~> 2.1.5’
pod ‘AliyunPlayer_iOS/AliyunPlayerSDK’
pod ‘YYModel’
pod ‘KSGuaidView’
pod ‘Bugly’
pod ‘VODUpload’
pod ‘AlivcLivePusher’,’~> 3.3.7’
pod ‘SocketRocket’
end
2.在.pch文件里引入文件头
例:
#import
#import “SDCycleScrollView.h”
#import
#import
#import
#import “UIView+Extension.h”
#import “UIImage+Extension.h”
#import
#import “NSString+Utils.h”
#import “SDCycleScrollView.h”
//************* 创建一个baseVC*************
创建一个基础的VC,让所有的VC都继承他,有利于设置一些公共属性
//*************** 创建一个继承UINavigationController的VC ******************
创建一个继承UINavigationController的VC是为了自定义导航栏
.m文件的内容
#define enableDrag (self.viewControllers.count > 1 && !self.disableDragBack&&self.isCanBack)
typedef NS_ENUM(int, ATNavMovingStateEnumes) {
ATNavMovingStateStanby = 0,
ATNavMovingStateDragBegan,
ATNavMovingStateDragChanged,
ATNavMovingStateDragEnd,
ATNavMovingStateDecelerating,
};
@interface ATNavigationController ()
{
}
/**
//@property(nonatomic,assign)BOOL ispush;
@end
@implementation ATNavigationController
(NSMutableDictionary *)screenShotsDict {
if (_screenShotsDict == nil) {
_screenShotsDict = [NSMutableDictionary dictionary];
}
return _screenShotsDict;
}
-(UIView *)backgroundView {
if (_backgroundView == nil) {
_backgroundView = [[UIView alloc]initWithFrame:self.view.bounds];
_backgroundView.backgroundColor = [UIColor blackColor];
_lastScreenShotView = [[UIImageView alloc] initWithFrame:_backgroundView.bounds];
_lastScreenShotView.backgroundColor = [UIColor whiteColor];
[_backgroundView addSubview:_lastScreenShotView];
_lastScreenBlackMask = [[UIView alloc] initWithFrame:_backgroundView.bounds];
_lastScreenBlackMask.backgroundColor = [UIColor blackColor];
[_backgroundView addSubview:_lastScreenBlackMask];
}
if (_backgroundView.superview == nil) {
[self.view.superview insertSubview:_backgroundView belowSubview:self.view];
}
return _backgroundView;
}
-(void)viewDidLoad
{
[super viewDidLoad];
// self.ispush = YES;
// 为导航控制器view,添加拖拽手势
self.pan = [[UIPanGestureRecognizer alloc] init];
[self.pan addTarget:self action:@selector(paningGestureReceive:)];
[self.pan setDelegate:self];
[self.pan delaysTouchesBegan];
[self.view addGestureRecognizer:self.pan];
[self.navigationBar setBackgroundImage:[UIImage createImageWithColor:UIColorWhite ] forBarMetrics:UIBarMetricsDefault];
// self.navigationBar.titleTextAttributes = @{NSForegroundColorAttributeName: [UIColor darkTextColor],NSFontAttributeName: [UIFont systemFontOfSize:18]};
self.navigationBar.titleTextAttributes = @{NSForegroundColorAttributeName: [UIColor blackColor],NSFontAttributeName: [UIFont systemFontOfSize:18]};
// self.navigationBar.barStyle = UIBaselineAdjustmentNone;
//去掉分割线
// [self.navigationBar setShadowImage:[UIImage createImageWithColor:UIColorGray] size:CGSizeMake(self.view.frame.size.width, 0.5)]];
// [self.navigationBar setShadowImage:[UIImage createImageWithColor:UIColorMakeWithHex(@"#dddddd")]];
// [[UINavigationBar appearance] setShadowImage:[[UIImage alloc] init]];
[[UINavigationBar appearance] setShadowImage:[UIImage createImageWithColor:LINECOLOR]];
[self.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName : UIColorMakeWithHex(@"#222123"),
NSFontAttributeName : [UIFont fontWithName:@"Helvetica-Bold" size:20]}];
self.isCanBack = YES;
self.interactivePopGestureRecognizer.delegate = self;
}
-(BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer {
if (self.viewControllers.count <= 1 ) {
return NO;
}
return self.pan;
}
-(void)dealloc {
self.screenShotsDict = nil;
[self.backgroundView removeFromSuperview];
self.backgroundView = nil;
}
#pragma mark - 截屏相关方法
/**
#pragma mark - 监听导航栏栈控制器改变 截屏
/**
push前添加当前界面截屏
*/
-(void)pushViewController:(UIViewController *)viewController animated:(BOOL)animated
{
if (self.viewControllers.count > 0)
{
[self.screenShotsDict setObject:[self capture] forKey:[self pointer:self.topViewController]];
viewController.navigationItem.leftBarButtonItem = [UIBarButtonItem itemWithTarget:self action:@selector(back) image:@"ogin_ic_re_turn@3x" highImage:@"ogin_ic_re_turn@3x"];
// 自动显示或隐藏tabbar
viewController.hidesBottomBarWhenPushed = YES;
}
[super pushViewController:viewController animated:animated];
}
-(void)back
{
[self.aTNavigationControllerdelegate backClick];
if (self.isCanBack) {
[self popViewControllerAnimated:YES];
NSLog(@"bb");
}
NSLog(@"nn");
}
/**
(UIViewController *)popViewControllerAnimated:(BOOL)animated {
UIViewController popVc = [super popViewControllerAnimated:animated];
[self.screenShotsDict removeObjectForKey:[self pointer:self.topViewController]];
return popVc;
}
/*
重置界面的截屏(新增了界面会缺失截屏)
*/
-(void)setViewControllers:(NSArray *)viewControllers animated:(BOOL)animated
{
if ([viewControllers containsObject:self.topViewController]) {
[self.screenShotsDict setObject:[self capture] forKey:[self pointer:self.topViewController]];
}
[super setViewControllers:viewControllers animated:animated];
NSMutableDictionary *newDic = [NSMutableDictionary dictionary];
for (UIViewController *vc in viewControllers) {
id obj = [self.screenShotsDict objectForKey:[self pointer:vc]];
if (obj) {
[newDic setObject:obj forKey:[self pointer:vc]];
}
}
self.screenShotsDict = newDic;
}
#pragma mark - 拖拽移动界面
-(void)moveViewWithX:(float)x
{
// 设置水平位移在 [0, ATNavViewW] 之间
x = MAX(MIN(x, ATNavViewW), 0);
// 设置frame的x
self.view.frame = (CGRect){ {x, self.view.frame.origin.y}, self.view.frame.size};
// 设置黑色蒙版的不透明度
self.lastScreenBlackMask.alpha = 0.6 * (1 - (x / ATNavViewW));
// 设置上一个截屏的缩放比例
CGFloat scale = x / ATNavViewW * 0.05 + 0.95;
self.lastScreenShotView.transform = CGAffineTransformMakeScale(scale, scale);
// 移动键盘
if (([[[UIDevice currentDevice] systemVersion] floatValue] >= 9)) {
[[[UIApplication sharedApplication] windows] enumerateObjectsUsingBlock:^(__kindof UIWindow * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
if ([obj isKindOfClass:NSClassFromString(@"UIRemoteKeyboardWindow")]) {
[(UIWindow *)obj setTransform:CGAffineTransformMakeTranslation(x, 0)];
}
}];
}
else {
if ([[[UIApplication sharedApplication] windows] count] > 1) {
[((UIWindow *)[[[UIApplication sharedApplication] windows] objectAtIndex:1]) setTransform:CGAffineTransformMakeTranslation(x, 0)];
}
}
}
-(void)paningGestureReceive:(UIPanGestureRecognizer *)recoginzer
{
if (!enableDrag) return;
if (UIGestureRecognizerStateBegan == recoginzer.state) {
[self.view endEditing:YES];
if (self.movingState == ATNavMovingStateStanby) {
self.movingState = ATNavMovingStateDragBegan;
self.backgroundView.hidden = NO;
self.lastScreenShotView.image = [self lastScreenShot];
}
}else if (recoginzer.state == UIGestureRecognizerStateEnded || recoginzer.state == UIGestureRecognizerStateCancelled){
if (self.movingState == ATNavMovingStateDragBegan || self.movingState == ATNavMovingStateDragChanged) {
self.movingState = ATNavMovingStateDragEnd;
[self panGestureRecognizerDidFinish:recoginzer];
}
} else if (recoginzer.state == UIGestureRecognizerStateChanged) {
if (self.movingState == ATNavMovingStateDragBegan || self.movingState == ATNavMovingStateDragChanged) {
self.movingState = ATNavMovingStateDragChanged;
[self moveViewWithX:[recoginzer translationInView:ATKeyWindow].x];
}
}
}
-(void)panGestureRecognizerDidFinish:(UIPanGestureRecognizer *)panGestureRecognizer {
#define decelerationTime (0.4)
// 获取手指离开时候的速率
CGFloat velocityX = [panGestureRecognizer velocityInView:ATKeyWindow].x;
// 手指拖拽的距离
CGFloat translationX = [panGestureRecognizer translationInView:ATKeyWindow].x;
// 按照一定decelerationTime的衰减时间,计算出来的目标位置
CGFloat targetX = MIN(MAX(translationX + (velocityX * decelerationTime / 2), 0), ATNavViewW);
// 是否pop
BOOL pop = ( targetX > ATMinX );
// 设置动画初始化速率为当前瘦子离开的速率
CGFloat initialSpringVelocity = fabs(velocityX) / (pop ? ATNavViewW - translationX : translationX);
self.movingState = ATNavMovingStateDecelerating;
[UIView animateWithDuration:ATAnimationDuration
delay:0
usingSpringWithDamping:1
initialSpringVelocity:initialSpringVelocity
options:UIViewAnimationOptionCurveEaseOut
animations:^{
[self moveViewWithX:pop ? ATNavViewW : 0];
} completion:^(BOOL finished) {
self.backgroundView.hidden = YES;
if ( pop ) {
[self popViewControllerAnimated:NO];
}
self.view.frame = (CGRect){ {0, self.view.frame.origin.y}, self.view.frame.size };
self.movingState = ATNavMovingStateStanby;
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)((pop ? 0.3f : 0.0f) * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
// 移动键盘
if (([[[UIDevice currentDevice] systemVersion] floatValue] >= 9)) {
[[[UIApplication sharedApplication] windows] enumerateObjectsUsingBlock:^(__kindof UIWindow * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
if ([obj isKindOfClass:NSClassFromString(@"UIRemoteKeyboardWindow")]) {
[(UIWindow *)obj setTransform:CGAffineTransformIdentity];
}
}];
}
else {
if ([[[UIApplication sharedApplication] windows] count] > 1) {
[((UIWindow *)[[[UIApplication sharedApplication] windows] objectAtIndex:1]) setTransform:CGAffineTransformIdentity];
}
}
});
}];
}
#pragma mark - 拖拽手势代理
/**
-(void)addpang
{
if (self.pan)
{
return;
}
// 为导航控制器view,添加拖拽手势
self.pan = [[UIPanGestureRecognizer alloc] init];
[self.pan addTarget:self action:@selector(paningGestureReceive:)];
[self.pan setDelegate:self];
[self.pan delaysTouchesBegan];
[self.view addGestureRecognizer:self.pan];
}
-(void)removepang
{
if (self.pan)
{
[self.view removeGestureRecognizer:self.pan];
self.pan = nil;
}
}
/**
. h文件
#define ATKeyWindow [[UIApplication sharedApplication] keyWindow]
#define ATNavViewW [UIScreen mainScreen].bounds.size.width
#define ATAnimationDuration 0.5f
#define ATMinX (0.3f * ATNavViewW)
@protocol ATNavigationControllerdelegate
-(void)backClick;
@end
@interface ATNavigationController : UINavigationController
/**
@property (nonatomic, retain) UIPanGestureRecognizer *pan;
@property (nonatomic, strong) UIButton *rightButton;
@property (nonatomic, strong) UIButton *leftButton;
@property (nonatomic, assign) BOOL isCanBack;
@property (weak, nonatomic) id aTNavigationControllerdelegate;
-(void)addpang;
-(void)removepang;
+(instancetype)shareNav;
//************** 创建一个继承UITabBarController的VC**************
创建一个继承UITabBarController的VC是为了便于自定义BarItem
例:
先倒入继承UINavigationController的VC的头文件
.m文件的内容
-(void)viewDidLoad {
[super viewDidLoad];
[AppDelegate sharedApp].rootNavi.viewControllers = [NSArray arrayWithObjects:self, nil];
MainPageViewController *mainPageVC = [[MainPageViewController alloc] init];
[self addChildVc:mainPageVC WithTitle:@"首页" image:@"home_tab_ic_sy_nor@2x" selectedImage:@"home_tab_ic_sy_sel@2x"];
CourseViewController * courseVC = [[CourseViewController alloc] init];
[self addChildVc:courseVC WithTitle:@"我的课程" image:@"course_nor@2x" selectedImage:@"course_sel@2x"];
NewMainPageViewController *mainPageVC = [[NewMainPageViewController alloc] init];
[self addChildVc:mainPageVC WithTitle:@"首页" image:@"home_tab_ic_sy_nor@2x" selectedImage:@"home_tab_ic_sy_sel@2x"];
LiveListViewController * courseVC = [[LiveListViewController alloc] init];
[self addChildVc:courseVC WithTitle:@"线上课程" image:@"home_tab_ic_zb_nor@2x" selectedImage:@"home_tab_ic_zb_sel@2x"];
MineViewController *minePage = [[MineViewController alloc] init];
[self addChildVc:minePage WithTitle:@"我的" image:@"home_tab_ic_wo_nor@2x" selectedImage:@"home_tab_ic_wo_sel@2x"];
[[UITabBar appearance] setBackgroundColor:[UIColor whiteColor]];
}
/**
添加一个自控制器
@param childVc 子控制器
@param title 标题
@param image 图片
@param selImage 选中的图片
*/
-(void)addChildVc:(UIViewController *)childVc WithTitle:(NSString *)title image:(NSString *)image selectedImage:(NSString *)selImage
{
//底部bar设置文字
childVc.tabBarItem.title = title;
childVc.title = title;
childVc.tabBarItem.image = [[[UIImage imageNamed:image ]scaleToSize:CGSizeMake(24, 24)] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
childVc.tabBarItem.selectedImage = [[[UIImage imageNamed:selImage] scaleToSize:CGSizeMake(24, 24)]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
NSMutableDictionary *textattr = [NSMutableDictionary dictionary];
textattr[NSForegroundColorAttributeName] = UIColorMake(153, 153, 153);
NSMutableDictionary *seletedTextattr = [NSMutableDictionary dictionary];
childVc.tabBarItem.titlePositionAdjustment = UIOffsetMake(0, -4);
childVc.tabBarItem.imageInsets = UIEdgeInsetsMake(-1, 0, 1, 0);
seletedTextattr[NSForegroundColorAttributeName] = MAINCOLOR;
[childVc.tabBarItem setTitleTextAttributes:textattr forState:UIControlStateNormal];
[childVc.tabBarItem setTitleTextAttributes:seletedTextattr forState:UIControlStateSelected];
ATNavigationController *nav = [[ATNavigationController alloc] initWithRootViewController:childVc];
[self addChildViewController:nav];
}
//***************** 创建一个网络请求的类 *****************
创建一个网络请求的类是为了方便数据请求
.m文件
例:
#define ACCEPTTYPENORMAL @[@“application/json”,@“application/xml”,@“text/json”,@“text/javascript”,@“text/html”,@“text/plain”]
#define ACCEPTTYPEIMAGE @[@“text/plain”, @“multipart/form-data”, @“application/json”, @“text/html”, @“image/jpeg”, @“image/png”, @“application/octet-stream”, @“text/json”]
@interface HttpRequestTool()
@property (strong,nonatomic)AFHTTPSessionManager *manager;
@end
@implementation HttpRequestTool
+(HttpRequestTool *)shareAssistant{
static dispatch_once_t onceToken;
static HttpRequestTool *assistant = nil;
if (assistant == nil) {
dispatch_once(&onceToken, ^{
assistant = [[HttpRequestTool alloc]init];
});
}
return assistant;
}
-(instancetype)init{
self = [super init];
if (self) {
// [managr.requestSerializer willChangeValueForKey:@“timeoutInterval”];
// managr.requestSerializer.timeoutInterval = 30.f;
// [managr.requestSerializer didChangeValueForKey:@“timeoutInterval”];
_manager = [AFHTTPSessionManager manager];
_manager.requestSerializer=[AFHTTPRequestSerializer serializer];
// _manager.requestSerializer= [AFHTTPRequestSerializer serializer];
NSDate* date = [NSDate dateWithTimeIntervalSinceNow:0];//获取当前时间0秒后的时间
NSTimeInterval time=[date timeIntervalSince1970]*1000;// *1000 是精确到毫秒,不乘就是精确到秒
NSString *timeString = [NSString stringWithFormat:@"%.0f", time];
NSString *net_ip = [MYTool getIPAddress:YES];
NSString *host_ip = [MYTool getHostIPAddress:YES];
NSString *netType=[[MyTool sharedInstance] getNetworkType];
[_manager.requestSerializer setTimeoutInterval:5];
[_manager.requestSerializer setValue:@"iOS" forHTTPHeaderField:@"User-Agent"];
[_manager.requestSerializer setValue:AppVersion forHTTPHeaderField:@"app-version"];
[_manager.requestSerializer setValue:DeviceUUID forHTTPHeaderField:@"device-uuid"];
[_manager.requestSerializer setValue:DeviceType forHTTPHeaderField:@"device-type"];
[_manager.requestSerializer setValue:DeviceName forHTTPHeaderField:@"device-name"];
[_manager.requestSerializer setValue: SystemName forHTTPHeaderField:@"system-name"];
[_manager.requestSerializer setValue:DeviceVersion forHTTPHeaderField:@"system-version"];
[_manager.requestSerializer setValue:timeString forHTTPHeaderField:@"access-time"];
[_manager.requestSerializer setValue:netType forHTTPHeaderField:@"net-type"];
[_manager.requestSerializer setValue:host_ip forHTTPHeaderField:@"host-ip"];
[_manager.requestSerializer setValue:net_ip forHTTPHeaderField:@"net-ip"];
NSLog(@"app_version=%@ \n device_uuid=%@ \n device_type=%@\n device_name=%@\n system_name=%@\n system_version=%@\n access_time=%@\n net_type=%@ \n host_ip=%@ \n net_ip=%@",AppVersion,DeviceUUID,DeviceType,DeviceName,SystemName,DeviceVersion,timeString,netType,host_ip,net_ip);
_manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/json",@"text/javascript",@"text/html",@"multipart/form-data",@"text/plain",nil,nil];
}
return self;
}
(void)get:(NSString *)url params:(NSDictionary *)params success:(void(^)(id response))success failure:(void(^)(NSError *error))failure
{
AFHTTPSessionManager *managr = [AFHTTPSessionManager manager];
managr.responseSerializer = [AFHTTPResponseSerializer serializer];
// managr.responseSerializer.acceptableContentTypes=[NSSet setWithObjects:@“text/html”,@“application/json”, nil];
[managr GET:url parameters:params progress:^(NSProgress * _Nonnull downloadProgress) {
} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSError *err = nil;
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:&err];
if (!err) {
if (success) {
success(dict);
}
}
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
if (failure) {
failure(error);
}
}];
}
-(void)post:(NSString *)url params:(NSMutableDictionary *)params success:(void(^)(id response))success failure:(void(^)(NSError *error))failure
{
UIWindow *keywindow = [[[UIApplication sharedApplication] delegate] window];
[MBProgressHUD hideHUDForView:keywindow animated:YES];
MBProgressHUD *hud=nil;
hud = [MBProgressHUD showHUDAddedTo:keywindow animated:YES];
hud.labelText = @"正在努力加载中...";
NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
params[@"user_token"] = [defaults objectForKey:@"user_token"];
if ([[defaults objectForKey:@"user_token"] length]==0) {
params[@"user_token"] = @"";
}
[_manager POST:url parameters:params progress:^(NSProgress * _Nonnull uploadProgress) {
} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSLog(@"params:%@\n url:%@\n responseObject:%@",params,url,responseObject);
[MBProgressHUD hideHUDForView:keywindow animated:YES];
//json解析
NSError *err = nil;
NSDictionary *dict = [self nullDic:responseObject];
// NSDictionary *dict = [self nullDic:[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:&err]];
if (!err) {
if (success) {
//数据反射
success(dict);
}
}
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
[MBProgressHUD hideHUDForView:keywindow animated:YES];
NSLog(@"params:%@\n url:%@\n responseObject:%@",params,url,error);
if (failure) {
failure(error);
}
}];
}
-(NSMutableDictionary *)md5Sign:(NSMutableDictionary )dic andUrl:(NSString) url{
NSMutableArray *numArray = [NSMutableArray arrayWithArray:dic.allKeys];
[numArray sortUsingComparator: ^NSComparisonResult (NSString *obj1, NSString *obj2) {
return (NSComparisonResult)[obj1 compare:obj2 options:NSNumericSearch];
}];
NSMutableString *signStrs = [[NSMutableString alloc] init];;
[signStrs appendString:SIGN];
[signStrs appendString:[url lowercaseString]];
for (NSString *key in numArray) {
[signStrs appendString:key];
[signStrs appendString:[self changeType:[dic objectForKey:key]]];
}
NSString *signStr = [self md5:signStrs];
dic[@“sign”] = signStr;
return dic;
}
-(NSString *)md5:(NSString *)str
{
const char *cStr = [str UTF8String];
unsigned char result[16];
CC_MD5( cStr, (unsigned int)strlen(cStr), result );
NSString *str1 = [NSString stringWithFormat:@"%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X",
result[0], result[1], result[2], result[3],
result[4], result[5], result[6], result[7],
result[8], result[9], result[10], result[11],
result[12], result[13], result[14], result[15]
];
NSString *newStr = [str1 lowercaseString];
return newStr;
}
#pragma mark - 私有方法
//将NSDictionary中的Null类型的项目转化成@""
-(NSDictionary *)nullDic:(NSDictionary *)myDic
{
NSArray *keyArr = [myDic allKeys];
NSMutableDictionary *resDic = [[NSMutableDictionary alloc]init];
for (int i = 0; i < keyArr.count; i ++)
{
id obj = [myDic objectForKey:keyArr[i]];
obj = [self changeType:obj];
[resDic setObject:obj forKey:keyArr[i]];
}
return resDic;
}
//将NSDictionary中的Null类型的项目转化成@""
-(NSArray *)nullArr:(NSArray *)myArr
{
NSMutableArray *resArr = [[NSMutableArray alloc] init];
for (int i = 0; i < myArr.count; i ++)
{
id obj = myArr[i];
obj = [self changeType:obj];
[resArr addObject:obj];
}
return resArr;
}
//将NSString类型的原路返回
-(NSString *)stringToString:(NSString *)string
{
return string;
}
//将Null类型的项目转化成@""
-(NSString *)nullToString
{
return @"";
}
#pragma mark - 公有方法
//类型识别:将所有的NSNull类型转化成@""
-(id)changeType:(id)myObj
{
if ([myObj isKindOfClass:[NSDictionary class]])
{
return [self nullDic:myObj];
}
else if([myObj isKindOfClass:[NSArray class]])
{
return [self nullArr:myObj];
}
else if([myObj isKindOfClass:[NSString class]])
{
return [self stringToString:myObj];
}
else if([myObj isKindOfClass:[NSNull class]])
{
return [self nullToString];
} else if([myObj isKindOfClass:[NSNumber class]])
{
return [NSString stringWithFormat:@"%@",myObj];;
}
else
{
return myObj;
}
}
-(NSString *)jsonstring:(NSDictionary *)params{
NSString *jsonstr = nil;
if(params == nil){
jsonstr = @"";
}
else{
NSError *parseError = [NSError new];
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:params options:kNilOptions error:&parseError];
jsonstr = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}
return jsonstr;
}
-(void)postImg:(NSString *)url withImg:(UIImage *)image success:(void(^)(id response))success failure:(void(^)(NSError *error))failure{
UIWindow *keywindow = [[[UIApplication sharedApplication] delegate] window];
[MBProgressHUD hideHUDForView:keywindow animated:YES];
MBProgressHUD *hud=nil;
hud = [MBProgressHUD showHUDAddedTo:keywindow animated:YES];
hud.labelText = @"上传图片中...";
_manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/json",@"text/javascript",@"text/html",@"multipart/form-data",nil,nil];
[_manager POST:url parameters:nil constructingBodyWithBlock:^(id _Nonnull formData) {
NSDate *date = [NSDate date];
NSDateFormatter *formormat = [[NSDateFormatter alloc]init];
[formormat setDateFormat:@"HHmmss"];
NSString *dateString = [formormat stringFromDate:date];
NSString *fileName = [NSString stringWithFormat:@"%@.png",dateString];
NSData *imageData = UIImageJPEGRepresentation(image, 1);
double scaleNum = (double)300*1024/imageData.length;
// NSLog(@“图片压缩率:%f”,scaleNum);
if(scaleNum <1){
imageData = UIImageJPEGRepresentation(image, scaleNum);
}else{
imageData = UIImageJPEGRepresentation(image, 0.1);
}
[formData appendPartWithFileData:imageData name:@"image" fileName:fileName mimeType:@"image/jpg/png/jpeg"];
} progress:^(NSProgress * _Nonnull uploadProgress) {
NSLog(@"---%@",uploadProgress);
} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
[MBProgressHUD hideHUDForView:keywindow animated:YES];
if (success) {
//数据反射
success(responseObject);
}
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
[MBProgressHUD hideHUDForView:keywindow animated:YES];
if (failure) {
failure(error);
}
}];
}
(void)MyPosNoLoading:(NSString *)url params:(NSMutableDictionary *)params success:(void(^)(id response))success failure:(void(^)(NSError *error))failure{
NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
params[@“user_token”] = [defaults objectForKey:@“user_token”];//@“fc105c62489cc82d2166fa9d9d3cccda”;//[defaults objectForKey:@“user_token”];
if ([[defaults objectForKey:@“user_token”] length]==0) {
params[@“user_token”] = @"";
params[@“versions”] = [NSString stringWithFormat:@“v%@”,AppVersion];
params[@“uuid”] = DeviceUUID;
}
if ([url containsString:ApplePayNotif]||[url containsString:iOSYoCoinPayNotify]) {
NSLog(@"回调接口...");
[_manager.requestSerializer setTimeoutInterval:40];
}else{
NSLog(@"非回调接口...");
[_manager.requestSerializer setTimeoutInterval:15];
}
[_manager POST:url parameters:params progress:^(NSProgress * _Nonnull uploadProgress) {
} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSLog(@"successPostparams:%@\n url:%@\n responseObject:%@",params,url,responseObject);
NSLog(@"successPostparamsurl %@",url);
NSError *err = nil;
NSDictionary *dict = [self nullDic:responseObject];
if (!err) {
if (success) {
//数据反射
int code = [dict[@"code"] intValue];
if (code == 10000) {
success(dict);
if ([[UserDefault objectForKey:@"user_token"] length]!=0) {
[[NSNotificationCenter defaultCenter] postNotificationName:@"check_TokenExprice" object:@(code)];
}
}else{
success(dict);
}
}
}
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(@"failurePostparams:%@\n url:%@\n responseObject:%@",params,url,error);
NSLog(@"failurePosturl %@",url);
if (failure) {
failure(error);
}
}];
}
-(void)MyGetNoLoading:(NSString *)url params:(NSMutableDictionary *)params success:(void(^)(id response))success failure:(void(^)(NSError *error))failure{
NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
params[@"user_token"] = [defaults objectForKey:@"user_token"];
if ([[defaults objectForKey:@"user_token"] length]==0) {
params[@"user_token"] = @"";
// params[@“versions”] = [NSString stringWithFormat:@“v%@”,AppVersion];
}
params[@“uuid”] = DeviceUUID;
_manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/json",@"text/javascript",@"text/html",@"multipart/form-data",@"text/plain",nil,nil];
[_manager GET:url parameters:params progress:^(NSProgress * _Nonnull downloadProgress) {
} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSLog(@"successGet:params:%@\n url:%@\n responseObject:%@",params,url,responseObject);
NSError *err = nil;
NSDictionary *dict = [self nullDic:responseObject];
if (!err) {
if (success) {
//数据反射
int code = [dict[@"code"] intValue];
if (code == 10000) {
if ([[UserDefault objectForKey:@"user_token"] length]!=0) {
[[NSNotificationCenter defaultCenter] postNotificationName:@"check_TokenExprice" object:@(code)];
}
success(dict);
}else{
success(dict);
}
}
}
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(@"failureGet:params:%@\n url:%@\n responseObject:%@",params,url,error);
if (failure) {
failure(error);
}
}];
}
-(void)cancelTask{
[self.manager.operationQueue cancelAllOperations];
}
-(void)postImg:(NSString *)url withImg:(UIImage *)img andImgs:(NSArray *)imgs params:(NSMutableDictionary *)params Imageparam:(NSString *)imageparam success:(void(^)(id response))success failure:(void(^)(NSError *error))failure{
UIWindow *keywindow = [[[UIApplication sharedApplication] delegate] window];
[MBProgressHUD hideHUDForView:keywindow animated:YES];
MBProgressHUD *hud=nil;
hud = [MBProgressHUD showHUDAddedTo:keywindow animated:YES];
hud.labelText = @"请稍后...";
NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
params[@"user_token"] = [defaults objectForKey:@"user_token"];//@"fc105c62489cc82d2166fa9d9d3cccda";//[defaults objectForKey:@"user_token"];
if ([[defaults objectForKey:@"user_token"] length]==0) {
params[@"user_token"] = @"";
}
_manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/json",@"text/javascript",@"text/html",@"multipart/form-data",nil,nil];
[_manager POST:url parameters:params constructingBodyWithBlock:^(id _Nonnull formData) {
NSLog(@"url== %@ %@",url,params);
NSDate *date = [NSDate date];
NSDateFormatter *formormat = [[NSDateFormatter alloc]init];
[formormat setDateFormat:@"HHmmss"];
NSString *dateString = [formormat stringFromDate:date];
if (img) {
NSString *fileName = [NSString stringWithFormat:@"%@.png",dateString];
NSData *imageData = UIImageJPEGRepresentation(img, 1);
double scaleNum = (double)300*1024/imageData.length;
if(scaleNum <1){
imageData = UIImageJPEGRepresentation(img, scaleNum);
}else{
imageData = UIImageJPEGRepresentation(img, 0.1);
}
if ([url containsString:SaveLiveGoods] ||[url containsString:AddUserLiveGoods]) {
NSLog(@"======introduceImage");
[formData appendPartWithFileData:imageData name:@"introduceImage" fileName:fileName mimeType:@"image/jpg/png/jpeg"];
}else if ([url containsString:AddSeriesLesson] ||[url containsString:EditSeriesLesson]) {
NSLog(@"======introduceImage");
[formData appendPartWithFileData:imageData name:@"image" fileName:fileName mimeType:@"image/jpg/png/jpeg"];
}else{
[formData appendPartWithFileData:imageData name:imageparam fileName:fileName mimeType:@"image/jpg/png/jpeg"];
}
}
if (imgs.count !=0) {
for (int i = 0; i< imgs.count; i++) {
NSString *fileNames = [NSString stringWithFormat:@"%d%@.png",i,dateString];
UIImage *imgd = imgs[i];
NSData *imageDatas = UIImageJPEGRepresentation(imgd, 1);
double scaleNums = (double)300*1024/imageDatas.length;
if(scaleNums <1){
imageDatas = UIImageJPEGRepresentation(imgd, scaleNums);
}else{
imageDatas = UIImageJPEGRepresentation(imgd, 0.1);
}
[formData appendPartWithFileData:imageDatas name:imageparam fileName:fileNames mimeType:@"image/jpg/png/jpeg"];
NSLog(@"fileNamesfileNames %@",fileNames);
}
}
} progress:^(NSProgress * _Nonnull uploadProgress) {
NSLog(@"---%@",uploadProgress);
} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
[MBProgressHUD hideHUDForView:keywindow animated:YES];
if (success) {
//数据反射
NSDictionary *dict = responseObject;
int code = [dict[@"code"] intValue];
if (code == 10000) {
success(dict);
if ([[UserDefault objectForKey:@"user_token"] length]!=0) {
[[NSNotificationCenter defaultCenter] postNotificationName:@"check_TokenExprice" object:@(code)];
}
}else{
success(dict);
}
}
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
[MBProgressHUD hideHUDForView:keywindow animated:YES];
NSLog(@"params=%@\n url= %@ \nreponse=%@",params,url,error);
if (failure) {
failure(error);
}
}];
}
-(void)postImgAndVideo:(NSString *)url withImg:(UIImage *)img andVideopath:(NSString *)videopath params:(NSMutableDictionary *)params Imageparam:(NSString *)imageparam Videoparam:(NSString *)videoparam success:(void(^)(id response))success failure:(void(^)(NSError *error))failure{
NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
params[@"user_token"] = [defaults objectForKey:@"user_token"];
if ([[defaults objectForKey:@"user_token"] length]==0) {
params[@"user_token"] = @"";
}
_manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/json",@"text/javascript",@"text/html",@"multipart/form-data",nil,nil];
[_manager POST:url parameters:params constructingBodyWithBlock:^(id _Nonnull formData) {
NSLog(@"url== %@ params==%@",url,params);
NSDate *date = [NSDate date];
NSDateFormatter *formormat = [[NSDateFormatter alloc]init];
[formormat setDateFormat:@"HHmmss"];
NSString *dateString = [formormat stringFromDate:date];
if (img) {
NSString *fileName = [NSString stringWithFormat:@"%@.png",dateString];
NSData *imageData = UIImageJPEGRepresentation(img, 1);
double scaleNum = (double)300*1024/imageData.length;
if(scaleNum <1){
imageData = UIImageJPEGRepresentation(img, scaleNum);
}else{
imageData = UIImageJPEGRepresentation(img, 0.1);
}
[formData appendPartWithFileData:imageData name:imageparam fileName:fileName mimeType:@"image/jpg/png/jpeg"];
}
} progress:^(NSProgress * _Nonnull uploadProgress) {
NSLog(@"---%@",uploadProgress);
} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
// [MBProgressHUD hideHUDForView:keywindow animated:YES];
if (success) {
//数据反射
NSDictionary *dict = responseObject;
int code = [dict[@"code"] intValue];
if (code == 10000) {
success(dict);
if ([[UserDefault objectForKey:@"user_token"] length]!=0) {
[[NSNotificationCenter defaultCenter] postNotificationName:@"check_TokenExprice" object:@(code)];
}
}else{
success(dict);
}
// success(responseObject);
}
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
// [MBProgressHUD hideHUDForView:keywindow animated:YES];
NSLog(@“params=%@\n url= %@ \nreponse=%@”,params,url,error);
if (failure) {
failure(error);
}
}];
}
.h文件
#import “AFNetworking.h”
#import
#import
#define ShareDefaultNetAssistant [AFNetWrokingAssistant shareAssistant]
@interface HttpRequestTool : NSObject
+(HttpRequestTool *)shareAssistant;
/**
/**
//+ (void)postTest:(NSString *)url params:(NSMutableDictionary *)params success:(void(^)(id response))success failure:(void(^)(NSError *error))failure;
//+ (void)postNew:(NSString *)url params:(NSMutableDictionary *)params success:(void(^)(id response))success failure:(void(^)(NSError *error))failure;
//上传图片
-(void)postImg:(NSString *)url withImg:(UIImage *)img success:(void(^)(id response))success failure:(void(^)(NSError *error))failure;
-(void)cancelTask;
//上传图片和视频
-(void)postImgAndVideo:(NSString *)url withImg:(UIImage *)img andVideopath:(NSString *)videopath params:(NSMutableDictionary *)params Imageparam:(NSString *)imageparam Videoparam:(NSString *)videoparam success:(void(^)(id response))success failure:(void(^)(NSError *error))failure;
-(void)postImg:(NSString *)url withImg:(UIImage *)img andImgs:(NSArray *)imgs params:(NSMutableDictionary *)params Imageparam:(NSString *)imageparam success:(void(^)(id response))success failure:(void(^)(NSError *error))failure;
-(void)MyPosNoLoading:(NSString *)url params:(NSMutableDictionary *)params success:(void(^)(id response))success failure:(void(^)(NSError *error))failure;
-(void)MyGetNoLoading:(NSString *)url params:(NSMutableDictionary *)params success:(void(^)(id response))success failure:(void(^)(NSError *error))failure;
//****************** 创建一个基础工具类******************
创建一个基础工具类是为了方便使用一些常用的方法
例:.m文件
+(instancetype)sharedInstance
{
return [[self alloc]init];
}
+(instancetype)allocWithZone:(struct _NSZone *)zone
{
static id instance = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
instance = [super allocWithZone:zone];
});
return instance;
}
下面创建自己需要的方法
//
-(NSString *)timestampSwitchTime:(NSInteger)timestamp andFormatter:(NSString *)format{
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateStyle:NSDateFormatterMediumStyle];
[formatter setTimeStyle:NSDateFormatterShortStyle];
[formatter setDateFormat:format]; // (@"YYYY-MM-dd hh:mm:ss")----------设置你想要的格式,hh与HH的区别:分别表示12小时制,24小时制
NSTimeZone *timeZone = [NSTimeZone timeZoneWithName:@"Asia/Beijing"];
[formatter setTimeZone:timeZone];
NSDate *confromTimesp = [NSDate dateWithTimeIntervalSince1970:timestamp];
NSLog(@"1296035591 = %@",confromTimesp);
NSString *confromTimespStr = [formatter stringFromDate:confromTimesp];
//NSLog(@"&&&&&&&confromTimespStr = : %@",confromTimespStr);
return confromTimespStr;
}
-(void)ShownMBProgressHUDSWith:(UIView *)view Message:(NSString *)message{
MBProgressHUD*hud = [MBProgressHUD showHUDAddedTo:view animated:YES];
hud.labelText = message?message:@“正在努力加载中…”;
}
-(void)HiddeMBProgressHUDWith:(UIView *)view{
[MBProgressHUD hideHUDForView:view animated:YES];
}
-(double)distanceBetweenOrderBy:(double)lat1 :(double)lat2 :(double)lng1 :(double)lng2{
double dd = M_PI/180;
double x1=lat1*dd,x2=lat2*dd;
double y1=lng1*dd,y2=lng2*dd;
double R = 6371004;
double distance = (2*R*asin(sqrt(2-2*cos(x1)*cos(x2)*cos(y1-y2) - 2*sin(x1)*sin(x2))/2));
//km 返回
//return distance*1000;
//返回 m
return distance;
}
-(BOOL)clearCacheWithFilePath:(NSString *)path{
NSString *directoryPath=[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];
NSArray *subpaths = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:directoryPath error:nil];
NSError *error = nil;
for (NSString *subPath in subpaths) {
NSString *filePath = [directoryPath stringByAppendingPathComponent:subPath];
[[NSFileManager defaultManager] removeItemAtPath:filePath error:nil];
if (error) {
return NO;
}
}
return YES;
}
/**
计算整个目录大小
*/
-(float)folderSizeAtPath
{
NSString *folderPath=[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];
NSFileManager * manager=[NSFileManager defaultManager ];
if (![manager fileExistsAtPath :folderPath]) {
return 0 ;
}
NSEnumerator *childFilesEnumerator = [[manager subpathsAtPath :folderPath] objectEnumerator ];
NSString * fileName;
long long folderSize = 0 ;
while ((fileName = [childFilesEnumerator nextObject ]) != nil ){
NSString * fileAbsolutePath = [folderPath stringByAppendingPathComponent :fileName];
folderSize += [ self fileSizeAtPath :fileAbsolutePath];
}
return folderSize/( 1024.0 * 1024.0 );
}
-(long long)fileSizeAtPath:(NSString *)filePath{
NSFileManager *manager = [NSFileManager defaultManager];
if ([manager fileExistsAtPath :filePath]){
return [[manager attributesOfItemAtPath :filePath error : nil ] fileSize];
}
return 0 ;
}
-(NSInteger)timeSwitchTimestamp:(NSString *)formatTime andFormatter:(NSString *)format{
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateStyle:NSDateFormatterMediumStyle];
[formatter setTimeStyle:NSDateFormatterShortStyle];
[formatter setDateFormat:format]; //(@"YYYY-MM-dd hh:mm:ss") ----------设置你想要的格式,hh与HH的区别:分别表示12小时制,24小时制
NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"Asia/Beijing"];
[formatter setTimeZone:timeZone];
NSDate* date = [formatter dateFromString:formatTime]; //------------将字符串按formatter转成nsdate
//时间转时间戳的方法:
NSInteger timeSp = [[NSNumber numberWithDouble:[date timeIntervalSince1970]] integerValue];
NSLog(@"将某个时间转化成 时间戳&&&&&&&timeSp:%ld",(long)timeSp); //时间戳的值
return timeSp;
}
-(NSString *)dateStringAfterlocalDateForYear:(NSInteger)year Month:(NSInteger)month Day:(NSInteger)day Hour:(NSInteger)hour Minute:(NSInteger)minute Second:(NSInteger)second CurrentTime:(NSDate *)curentTime Formatter:(NSString *)format
{
// 当前日期
NSDate *localDate = curentTime;//[NSDate date]; // 为伦敦时间
// 在当前日期时间加上 时间:格里高利历
NSCalendar *gregorian = [[NSCalendar alloc]initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
NSDateComponents *offsetComponent = [[NSDateComponents alloc]init];
[offsetComponent setYear:year ]; // 设置开始时间为当前时间的前x年
[offsetComponent setMonth:month];
[offsetComponent setDay:day];
[offsetComponent setHour:(hour+8)]; // 中国时区为正八区,未处理为本地,所以+8
[offsetComponent setMinute:minute];
[offsetComponent setSecond:second];
// 当前时间后若干时间
NSDate *minDate = [gregorian dateByAddingComponents:offsetComponent toDate:localDate options:0];
NSString *dateString = [NSString stringWithFormat:@"%@",minDate];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateStyle:NSDateFormatterMediumStyle];
[formatter setTimeStyle:NSDateFormatterShortStyle];
[formatter setDateFormat:format];
NSString *confromTimespStr = [formatter stringFromDate:minDate];
return dateString;
}
-(NSDate *)UTCDateFromLocalString:(NSString *)localString format:(NSString *)format{
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:format];
NSDate *date = [dateFormatter dateFromString:localString];
return date;
}
-(NSString *)getCurrentTimeWithFormatterStr:(NSString *)formatterStr{
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:formatterStr];
NSString *dateTime = [formatter stringFromDate:[NSDate date]];
return dateTime;
}
#pragma 正则匹配用户密码6-16位数字和字母组合
-(BOOL)checkPassword:(NSString *) password
{
// NSString *pattern = @"^(?![0-9]+ ) ( ? ! [ a − z A − Z ] + )(?![a-zA-Z]+ )(?![a−zA−Z]+)[a-zA-Z0-9]{6,18}";
//
// NSPredicate *pred = [NSPredicate predicateWithFormat:@“SELF MATCHES %@”, pattern];
// BOOL isMatch = [pred evaluateWithObject:password];
// return isMatch;
NSString *pattern = @"[0-9A-Za-z]{6,16}";
NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", pattern];
BOOL isMatch = [pred evaluateWithObject:password];
return isMatch;
}
#pragma 正则匹配手机号
-(BOOL)checkTelNumber:(NSString *) telNumber
{
NSString *pattern = @"^1+[3578]+\d{9}";
NSPredicate *pred = [NSPredicate predicateWithFormat:@“SELF MATCHES %@”, pattern];
BOOL isMatch = [pred evaluateWithObject:telNumber];
return isMatch;
}
#pragma mark 判断输入框是否全为空格
-(BOOL) isEmpty:(NSString *) str {
if (!str) {
return true;
} else {
NSCharacterSet *set = [NSCharacterSet whitespaceAndNewlineCharacterSet];
NSString *trimedString = [str stringByTrimmingCharactersInSet:set];
if ([trimedString length] == 0) {
return true;
} else {
return false;
}
}
}
-(UIImage *)ct_imageFromImage:(UIImage *)image inRect:(CGRect)rect{
CGSize size=image.size;
float a = rect.size.width/rect.size.height;
float X = 0;
float Y = 0;
float W = 0;
float H = 0;
if (size.width>size.height) {
H= size.height;
W= H*a;
Y=0;
X= (size.width - W)/2;
if ((size.width - size.height*a)/2<0) {
W = size.width;
H = size.width/a;
Y= (size.height-H)/2;
X=0;
}
}else{
W= size.width;
H= W/a;
X=0;
Y= (size.height - H)/2;
if ((size.height - size.width/a)/2<0) {
H= size.height;
W = size.height*a;
X= (size.width-W)/2;
Y=0;
}
}
//把像 素rect 转化为 点rect(如无转化则按原图像素取部分图片)
// CGFloat scale = [UIScreen mainScreen].scale;
// NSLog(@“qqq= w=%f h=%f X=%lf Y=%lf WW=%lf HH=%lf %lf”,size.width,size.height,X,Y,W,H,a);
// CGFloat x= rect.origin.xscale,y=rect.origin.yscale,w=rect.size.widthscale,h=rect.size.heightscale;
CGRect dianRect = CGRectMake(X, Y, W, H);//CGRectMake(x, y, w, h);
//截取部分图片并生成新图片
CGImageRef sourceImageRef = [image CGImage];
CGImageRef newImageRef = CGImageCreateWithImageInRect(sourceImageRef, dianRect);
UIImage *newImage = [UIImage imageWithCGImage:newImageRef scale:[UIScreen mainScreen].scale orientation:UIImageOrientationUp];
CGImageRelease(sourceImageRef);
// UIGraphicsEndImageContext();
return newImage;
}
#pragma mark 获取当前时间戳
-(NSString *)getNowTimeTimestamp{
NSDateFormatter *formatter = [[NSDateFormatter alloc] init] ;
[formatter setDateStyle:NSDateFormatterMediumStyle];
[formatter setTimeStyle:NSDateFormatterShortStyle];
[formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss SSS"]; // ----------设置你想要的格式,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]*1000];
return timeSp;
}
#pragma mark 获取当前时间戳
-(NSString *)getNowTimeTimestampWith:(NSString *)timeStr{
NSDateFormatter *formatter = [[NSDateFormatter alloc] init] ;
[formatter setDateStyle:NSDateFormatterMediumStyle];
[formatter setTimeStyle:NSDateFormatterShortStyle];
[formatter setDateFormat:timeStr]; // ----------设置你想要的格式,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;
}
-(NSDate *)UTCDateFromTimeStamap:(NSString *)timeStamap{
NSTimeInterval timeInterval=[timeStamap doubleValue];
// /1000;传入的时间戳timeStamap如果是精确到毫秒的记得要/1000
NSDate *UTCDate=[NSDate dateWithTimeIntervalSince1970:timeInterval];
return UTCDate;
}
//压缩图片为指定大小
-(UIImage *)compressImage:(UIImage *)image toByte:(NSUInteger)maxLength {
// Compress by quality
CGFloat compression = 1;
NSData *data = UIImageJPEGRepresentation(image, compression);
if (data.length < maxLength) return image;
CGFloat max = 1;
CGFloat min = 0;
for (int i = 0; i < 6; ++i) {
compression = (max + min) / 2;
data = UIImageJPEGRepresentation(image, compression);
if (data.length < maxLength * 0.9) {
min = compression;
} else if (data.length > maxLength) {
max = compression;
} else {
break;
}
}
UIImage *resultImage = [UIImage imageWithData:data];
if (data.length < maxLength) return resultImage;
// Compress by size
NSUInteger lastDataLength = 0;
while (data.length > maxLength && data.length != lastDataLength) {
lastDataLength = data.length;
CGFloat ratio = (CGFloat)maxLength / data.length;
CGSize size = CGSizeMake((NSUInteger)(resultImage.size.width * sqrtf(ratio)),
(NSUInteger)(resultImage.size.height * sqrtf(ratio))); // Use NSUInteger to prevent white blank
UIGraphicsBeginImageContext(size);
[resultImage drawInRect:CGRectMake(0, 0, size.width, size.height)];
resultImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
data = UIImageJPEGRepresentation(resultImage, compression);
}
return resultImage;
}
-(BOOL) IsIdentityCard:(NSString *)IDCardNumber
{
if (IDCardNumber.length <= 0) {
return NO;
}
NSString *regex2 = @"^(\d{14}|\d{17})(\d|[xX])$";
NSPredicate *identityCardPredicate = [NSPredicate predicateWithFormat:@“SELF MATCHES %@”,regex2];
return [identityCardPredicate evaluateWithObject:IDCardNumber];
}
-(void)ShownErrorButton:(UIView *)view{
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
// [button setImage:[[UIImage imageNamed:@“img_dm_1@3x”] scaleToSize:CGSizeMake(28, 19)] forState:UIControlStateSelected];
// [button setImage:[[UIImage imageNamed:@“img_dm_2@3x”] scaleToSize:CGSizeMake(28, 19)] forState:UIControlStateNormal];
[button addTarget:self action:@selector(verticalBarrageButton:) forControlEvents:UIControlEventTouchUpInside];
[view addSubview:button];
[button mas_makeConstraints:^(MASConstraintMaker *make) {
make.centerX.mas_equalTo(view);
make.centerY.mas_equalTo(view);
make.width.mas_equalTo (60);
make.width.mas_equalTo (30);
}];
button.layer.cornerRadius = 5;
button.backgroundColor = MAINCOLOR;
[button setTitle:@"" forState:UIControlStateNormal];
}
//urlEncode解码
-(NSString *)decoderUrlEncodeStr: (NSString *) input{
NSString *decodedString = @"";
if ([input containsString:@"%"]) {
decodedString = (__bridge_transfer NSString *)CFURLCreateStringByReplacingPercentEscapesUsingEncoding(NULL,(__bridge CFStringRef)input,CFSTR(""),CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding));
}
NSLog(@"decodedStringdecodedString %@ %@",decodedString,input);
if (decodedString.length==0) {
decodedString = input;
}
return decodedString;
// NSMutableString *outputStr = [NSMutableString stringWithString:input];
// [outputStr replaceOccurrencesOfString:@"+" withString:@"" options:NSLiteralSearch range:NSMakeRange(0,[outputStr length])];
// return [outputStr stringByRemovingPercentEncoding];
}
//urlEncode编码
-(NSString *)urlEncodeStr:(NSString *)input{
NSString charactersToEscape = @"?!@#$^&%+,:;=’"`<>()[]{}/\| ";
NSCharacterSet *allowedCharacters = [[NSCharacterSet characterSetWithCharactersInString:charactersToEscape] invertedSet];
NSString *upSign = [input stringByAddingPercentEncodingWithAllowedCharacters:allowedCharacters];
return upSign;
}
//获取当前window
-(UIWindow *)mainWindow
{
// UIApplication *app = [UIApplication sharedApplication];
// if ([app.delegate respondsToSelector:@selector(window)])
// {
// return [app.delegate window];
// }
// else
// {
// return [app keyWindow];
// }
UIWindow *window = [[[UIApplication sharedApplication] delegate] window];
return window;
}
-(void)copyWith:(NSString *)copyString{
UIPasteboard * pastboard = [UIPasteboard generalPasteboard];
pastboard.string = copyString;
}
-(void)SaveUserMessageWith:(NSDictionary *)data{
NSUserDefaults *userdefault = [NSUserDefaults standardUserDefaults];
[userdefault setObject:[data objectForKey:@"agent_id"] forKey:@"agent_id"];
[userdefault setObject:[data objectForKey:@"avatar_url"] forKey:@"avatarUrl"];
[userdefault setObject:[data objectForKey:@"city"] forKey:@"city"];
[userdefault setObject:[data objectForKey:@"country"] forKey:@"country"];
[userdefault setObject:[data objectForKey:@"headimgurl"] forKey:@"headimgurl"];
[userdefault setObject:[data objectForKey:@"is_bind_wechat"] forKey:@"is_bind_wechat"];
[userdefault setObject:[data objectForKey:@"is_live_user"] forKey:@"is_live_user"];
[userdefault setObject:[data objectForKey:@"is_set_password"] forKey:@"is_set_password"];
[userdefault setObject:[data objectForKey:@"is_vip"] forKey:@"is_vip"];
[userdefault setObject:[data objectForKey:@"mobile"] forKey:@"mobile"];
[userdefault setObject:[data objectForKey:@"predict_money"] forKey:@"predict_money"];
[userdefault setObject:[data objectForKey:@"province"] forKey:@"province"];
[userdefault setObject:[data objectForKey:@"register_time"] forKey:@"register_time"];
[userdefault setObject:[data objectForKey:@"sex"] forKey:@"sex"];
[userdefault setObject:[data objectForKey:@"sum_money"] forKey:@"sum_money"];
[userdefault setObject:[data objectForKey:@"today_course"] forKey:@"today_course"];
[userdefault setObject:[data objectForKey:@"today_money"] forKey:@"today_money"];
[userdefault setObject:[data objectForKey:@"tutor_fans"] forKey:@"tutor_fans"];
[userdefault setObject:[data objectForKey:@"user_id"] forKey:@"user_id"];
[userdefault setObject:[data objectForKey:@"user_token"] forKey:@"user_token"];
[userdefault setObject:[data objectForKey:@"username"] forKey:@"username"];
[userdefault setObject:[data objectForKey:@"vip_end_time"] forKey:@"vip_end_time"];
[userdefault setObject:[data objectForKey:@"vip_money"] forKey:@"vip_money"];
[userdefault setObject:[data objectForKey:@"wechat_unionid"] forKey:@"wechat_unionid"];
[userdefault setObject:[data objectForKey:@"tutor_code"] forKey:@"tutor_code"];
NSString *name = [MYTool decoderUrlEncodeStr:data[@"username"]];
NSLog(@"namename %@",name);
if (name.length ==0) {
name = [data objectForKey:@"username"];
[userdefault setObject:[data objectForKey:@"username"] forKey:@"username"];
}else{
if ([name containsString:@"%"]) {
name = [MYTool decoderUrlEncodeStr:name];
[userdefault setObject:name forKey:@"username"];
}else{
[userdefault setObject:name forKey:@"username"];
}
}
}
-(NSString *)getDeviceType{
struct utsname systemInfo;
uname(&systemInfo);
NSString *platform = [NSString stringWithCString:systemInfo.machine
encoding:NSUTF8StringEncoding];
//simulator
if ([platform isEqualToString:@"i386"]) return @"Simulator";
if ([platform isEqualToString:@"x86_64"]) return @"Simulator";
//iPhone
if ([platform isEqualToString:@"iPhone1,1"]) return @"IPhone_1G";
if ([platform isEqualToString:@"iPhone1,2"]) return @"IPhone_3G";
if ([platform isEqualToString:@"iPhone2,1"]) return @"IPhone_3GS";
if ([platform isEqualToString:@"iPhone3,1"]) return @"IPhone_4";
if ([platform isEqualToString:@"iPhone3,2"]) return @"IPhone_4";
if ([platform isEqualToString:@"iPhone4,1"]) return @"IPhone_4s";
if ([platform isEqualToString:@"iPhone5,1"]) return @"IPhone_5";
if ([platform isEqualToString:@"iPhone5,2"]) return @"IPhone_5";
if ([platform isEqualToString:@"iPhone5,3"]) return @"IPhone_5C";
if ([platform isEqualToString:@"iPhone5,4"]) return @"IPhone_5C";
if ([platform isEqualToString:@"iPhone6,1"]) return @"IPhone_5S";
if ([platform isEqualToString:@"iPhone6,2"]) return @"IPhone_5S";
if ([platform isEqualToString:@"iPhone7,1"]) return @"IPhone_6P";
if ([platform isEqualToString:@"iPhone7,2"]) return @"IPhone_6";
if ([platform isEqualToString:@"iPhone8,1"]) return @"IPhone_6s";
if ([platform isEqualToString:@"iPhone8,2"]) return @"IPhone_6s_P";
if ([platform isEqualToString:@"iPhone8,4"]) return @"IPhone_SE";
if ([platform isEqualToString:@"iPhone9,1"]) return @"IPhone_7";
if ([platform isEqualToString:@"iPhone9,3"]) return @"IPhone_7";
if ([platform isEqualToString:@"iPhone9,2"]) return @"IPhone_7P";
if ([platform isEqualToString:@"iPhone9,4"]) return @"IPhone_7P";
if ([platform isEqualToString:@"iPhone10,1"]) return @"IPhone_8";
if ([platform isEqualToString:@"iPhone10,4"]) return @"IPhone_8";
if ([platform isEqualToString:@"iPhone10,2"]) return @"IPhone_8P";
if ([platform isEqualToString:@"iPhone10,5"]) return @"IPhone_8P";
if ([platform isEqualToString:@"iPhone10,3"]) return @"IPhone_X";
if ([platform isEqualToString:@"iPhone10,6"]) return @"IPhone_X";
return nil;
}
-(BOOL)is_iPhoneX
{
struct utsname systemInfo;
uname(&systemInfo);
NSString *deviceString = [NSString stringWithCString:systemInfo.machine encoding:NSUTF8StringEncoding];
NSLog(@“deviceString== %@”,deviceString);
if (([deviceString isEqualToString:@“iPhone10,3”] || [deviceString isEqualToString:@“iPhone10,6”])) {
return YES;
}
return NO ;
}
-(void)setStatusBarBackgroundColor:(UIColor *)color {
UIView *statusBar = [[[UIApplication sharedApplication] valueForKey:@“statusBarWindow”] valueForKey:@“statusBar”];
NSLog(@“statusBar.backgroundColor—>%@”,statusBar.backgroundColor);
if ([statusBar respondsToSelector:@selector(setBackgroundColor:)]) {
statusBar.backgroundColor = color;
}
}
//存储
-(void)SaveDataWithFileName:(NSString *)filename InserteNSArray:(NSArray *)insertearray{
// NSString *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject;
NSString *fileName = [Path stringByAppendingPathComponent:filename];
[insertearray writeToFile:fileName atomically:YES];
}
//读取
-(NSArray *)readDataWithFileName:(NSString *)filename{
NSString *fileName = [Path stringByAppendingPathComponent:filename];
NSArray *result = [NSArray arrayWithContentsOfFile:fileName];
return result;
}
-(CGFloat)getRowWidth:(NSString *)title Font:(UIFont *)font Heigth:(CGFloat)heigth{
NSDictionary *dic = @{NSFontAttributeName:font};
CGRect rect =[title boundingRectWithSize:CGSizeMake(0, heigth) options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading attributes:dic context:nil];
return rect.size.width;
}
-(CGFloat)getRowHeigth:(NSString *)title Font:(UIFont *)font Width:(CGFloat)width{
NSDictionary *dic = @{NSFontAttributeName:font};
CGRect rect =[title boundingRectWithSize:CGSizeMake(width, 0) options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading attributes:dic context:nil];
return rect.size.height;
}
.h文件
+(instancetype)sharedInstance;
//获取网络类型
-(NSString *)getNetworkType;
//时间戳转成时间格式
//timestamp 传入的时间戳
//format 需要的时间格式
-(NSString *)timestampSwitchTime:(NSInteger)timestamp andFormatter:(NSString *)format;
//显示加载框
-(void)ShownMBProgressHUDSWith:(UIView *)view Message:(NSString *)message;
//隐藏加载框
-(void)HiddeMBProgressHUDWith:(UIView *)view;
//计算经纬度
-(double)distanceBetweenOrderBy:(double)lat1 :(double)lat2 :(double)lng1 :(double)lng2;
//清除缓存
-(BOOL)clearCacheWithFilePath:(NSString *)path;
// 整个缓存目录的大小
-(float)folderSizeAtPath;
//将某个时间段转成时间戳
//formatTime 传入的时间字符串
//format 传入的时间字符串的格式
-(NSInteger)timeSwitchTimestamp:(NSString *)formatTime andFormatter:(NSString *)format;
//获取当前时间
-(NSString *)getCurrentTimeWithFormatterStr:(NSString *)formatterStr;
//比较两个时间差
-(NSString *)dateStringAfterlocalDateForYear:(NSInteger)year Month:(NSInteger)month Day:(NSInteger)day Hour:(NSInteger)hour Minute:(NSInteger)minute Second:(NSInteger)second CurrentTime:(NSDate *)curentTime Formatter:(NSString *)format;
//时间转成date
-(NSDate *)UTCDateFromLocalString:(NSString *)localString format:(NSString *)format;
//检验密码
-(BOOL)checkPassword:(NSString *) password;
//检验手机号码
-(BOOL)checkTelNumber:(NSString *) telNumber;
//判断字符是否全为空格
-(BOOL) isEmpty:(NSString *) str;
//截取网络图片中间区域位置
//rect用来展示图片的imageview的rect
-(UIImage *)ct_imageFromImage:(UIImage *)image inRect:(CGRect)rect;
#pragma mark 获取当前时间戳
-(NSString *)getNowTimeTimestamp;
-(NSString *)getNowTimeTimestampWith:(NSString *)timeStr;
//时间戳专程NSdate
-(NSDate *)UTCDateFromTimeStamap:(NSString *)timeStamap;
//压缩图片为指定大小 maxLength:如压缩为2M,则传入2x1024 = 2048
-(UIImage *)compressImage:(UIImage *)image toByte:(NSUInteger)maxLength ;
//校验身份证
-(BOOL) IsIdentityCard:(NSString *)IDCardNumber;
//urlEncode解码
-(NSString *)decoderUrlEncodeStr: (NSString *) input;
//urlEncode编码
-(NSString *)urlEncodeStr:(NSString *)input;
//获取当前界面窗口
-(UIWindow *)mainWindow;
//复制到剪切板
-(void)copyWith:(NSString *)copyString;
//存储个人信息
-(void)SaveUserMessageWith:(NSDictionary *)data;
//判断手机型号
-(NSString *)getDeviceType;
//判断是iPhoneX
-(BOOL)is_iPhoneX;
//设置状态栏背景颜色
-(void)setStatusBarBackgroundColor:(UIColor *)color;
//plist存数据
-(void)SaveDataWithFileName:(NSString *)filename InserteNSArray:(NSArray *)insertearray;
//plist 读文件
-(NSArray *)readDataWithFileName:(NSString *)filename;
-(CGFloat)getRowWidth:(NSString *)title Font:(UIFont *)font Heigth:(CGFloat)heigth;
-(CGFloat)getRowHeigth:(NSString *)title Font:(UIFont *)font Width:(CGFloat)width;