iOS 搭建框架

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 <AFNetworking.h>
#import “SDCycleScrollView.h”
#import <Masonry/Masonry.h>
#import <UIImageView+WebCache.h>
#import <QMUIKit/QMUIKit.h>
#import “UIView+Extension.h”
#import “UIImage+Extension.h”
#import <Masonry/Masonry.h>
#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, strong) UIView lastScreenBlackMask;
    /
  • 顯示上一個界面的截屏
    /
    @property (nonatomic, strong) UIImageView lastScreenShotView;
    /
  • 顯示上一個界面的截屏黑色背景
    /
    @property (nonatomic,retain) UIView backgroundView;
    /
  • 存放截屏的字典數組 key:控制器指針字符串 value:截屏圖片
    /
    @property (nonatomic,retain) NSMutableDictionary screenShotsDict;
    /
  • 正在移動
    */
    @property (nonatomic,assign) ATNavMovingStateEnumes movingState;

//@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 - 截屏相關方法
/**

  • 當前導航欄界面截屏
    */
    -(UIImage )capture {
    UIView view = self.view;
    if (self.tabBarController) {
    view = self.tabBarController.view;
    }
    UIGraphicsBeginImageContextWithOptions(view.bounds.size, view.opaque, 0.0);
    [view.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage * img = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return img;
    }
    /
  • 得到OC對象的指針字符串
    /
    -(NSString )pointer:(id)objet {
    return [NSString stringWithFormat:@"%p", objet];
    }
    /
  • 獲取前一個界面的截屏
    */
    -(UIImage *)lastScreenShot {
    UIViewController *lastVC = [self.viewControllers objectAtIndex:self.viewControllers.count - 2];
    return [self.screenShotsDict objectForKey:[self pointer:lastVC]];
    }

#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");

}

/**

  • pop後移除當前界面截屏
    */
  • (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 - 拖拽手勢代理
/**

  • 不響應的手勢則傳遞下去
    */
    -(BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {
    return enableDrag;
    }

-(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;
}

}

/**

  • 優先響應其他手勢
    */
    -(BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRequireFailureOfGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {
    return YES;
    }

. 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
/**

  • If yes, disable the drag back, default no.
    */
    @property (nonatomic, assign) BOOL disableDragBack;

@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<AFMultipartFormData>  _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<AFMultipartFormData>  _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<AFMultipartFormData>  _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 <Foundation/Foundation.h>
#import <CommonCrypto/CommonDigest.h>
#define ShareDefaultNetAssistant [AFNetWrokingAssistant shareAssistant]
@interface HttpRequestTool : NSObject
+(HttpRequestTool *)shareAssistant;

/**

  • 發送一個GET請求
  • @param url 請求路徑
  • @param params 請求參數
  • @param success 請求成功後的回調(請將請求成功後想做的事情寫到這個block中)
  • @param failure 請求失敗後的回調(請將請求失敗後想做的事情寫到這個block中)
    */
  • (void)get:(NSString *)url params:(NSDictionary *)params success:(void(^)(id response))success failure:(void(^)(NSError *error))failure;

/**

  • 發送一個POST請求
  • @param url 請求路徑
  • @param params 請求參數
  • @param success 請求成功後的回調(請將請求成功後想做的事情寫到這個block中)
  • @param failure 請求失敗後的回調(請將請求失敗後想做的事情寫到這個block中)
    */
    -(void)post:(NSString *)url params:(NSMutableDictionary *)params success:(void(^)(id response))success failure:(void(^)(NSError *error))failure;
    -(NSMutableDictionary *)md5Sign:(NSMutableDictionary )dic andUrl:(NSString) url;
    -(NSString *)md5:(NSString *)str;

//+ (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]+)(?![azAZ]+)(?![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;

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章