123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794 |
- //
- // KSBaseWKWebViewController.m
- // KulexiuForTeacher
- //
- // Created by Kyle on 2022/3/17.
- //
- #import "KSBaseWKWebViewController.h"
- #import "WebViewBaseConfig.h" // 基础配置
- #import <KSToolLibrary/UIDevice+TFDevice.h> // 横竖屏
- // 其他web
- #import "KSLocalWebViewController.h"
- #import "KSAccompanyWebViewController.h"
- #import "AppDelegate+AppService.h"
- #import "UserInfoManager.h"
- #import "KSMediaManager.h"
- #import "KSUMShareManager.h"
- #import "KSOrderManager.h"
- #import "KSEnterLiveroomManager.h"
- // 保存文件
- #import <KSToolLibrary/KSICloudManager.h>
- #import <KSToolLibrary/KSDocumentViewController.h>
- // 聊天页面
- #import "KSChatConversationViewController.h"
- #import "KSGroupConversationController.h"
- #import "AddressListViewController.h"
- // 视频封面选择
- #import "KSVideoCropViewController.h"
- // 错误刷新web 页面
- #import "KSWebLoadRefreshView.h"
- #import "KSNewAlertView.h"
- #import "KSLogManager.h"
- typedef NS_ENUM(NSInteger, CHOOSETYPE) {
- CHOOSETYPE_XML,
- CHOOSETYPE_MIDI,
- CHOOSETYPE_MP3,
- CHOOSETYPE_ALL,
- };
- @interface KSBaseWKWebViewController ()<UIDocumentPickerDelegate,UIDocumentInteractionControllerDelegate>
- @property (nonatomic, assign) BOOL isOutLink; // 外部链接
- @property (nonatomic,weak) CALayer *progressLayer;
- @property (nonatomic, assign) BOOL hasModify;
- @property (nonatomic, assign) BOOL hasChangeSource; // 是否切换了亮屏,横屏等配置
- /// 选择本地文件 parm
- @property (nonatomic, strong) NSMutableDictionary *chooseFileParm;
- @property (nonatomic, strong) KSMediaManager *mediaManager;
- @property (strong, nonatomic) MBProgressHUD *HUD;
- @property (nonatomic, assign) CHOOSETYPE fileChooseType;
- @property (nonatomic, strong) NSString *bucketName;
- @property (nonatomic, assign) BOOL isFirstLoad;
- @property (nonatomic, strong) KSWebLoadRefreshView *errorView;
- @property (nonatomic, strong) KSUMShareManager *shareManager;
- @property (nonatomic, assign) BOOL isDownloadFile;
- @property (nonatomic, strong) KSNewAlertView *wifiAlert;
- // 是否需要重新加载
- @property (nonatomic, assign) BOOL needReload;
- @end
- @implementation KSBaseWKWebViewController
- - (void)viewDidLoad {
- [super viewDidLoad];
- // Do any additional setup after loading the view.
- self.ks_prefersNavigationBarHidden = YES; // 隐藏导航栏,其他事件额外处理
- [self initWebView];
- [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(operationDealCallbackMessage:) name:DEALCALLBACKNOTICIFATION object:nil];
- [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(backLoginView) name:@"liveroomBackRefresh" object:nil];
- self.isFirstLoad = YES;
- [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(captureViewTips:) name:UIScreenCapturedDidChangeNotification object:nil];
- }
- - (void)operationDealCallbackMessage:(NSNotification *)notification {
- NSString *status = [notification object];
- NSMutableDictionary *sendParm = [NSMutableDictionary dictionary];
- [sendParm setValue:@"paymentOperation" forKey:@"api"];
- NSMutableDictionary *content = [NSMutableDictionary dictionary];
- [content setValue:status forKey:@"status"];
- [sendParm setValue:content forKey:@"content"];
- [self postMessage:sendParm];
- }
- - (void)setParmDic:(NSDictionary *)parmDic {
- _parmDic = parmDic;
- _hasChangeSource = YES;
- BOOL isOpenLight = [parmDic ks_boolValueForKey:@"isOpenLight"];
- [[UIApplication sharedApplication] setIdleTimerDisabled:isOpenLight];
- // 横竖屏
- NSInteger orientation = [parmDic ks_integerValueForKey:@"orientation"];
-
- BOOL isLandScape = orientation == 0 ? YES : NO;
- self.ks_landScape = isLandScape;
- [self changeOrientation:isLandScape];
- }
- - (void)changeOrientation:(BOOL)isLandScape {
- if (isLandScape) {
- // 切换到横屏
- if (IS_IPAD) {
- self.zh_statusBarHidden = YES;
- }
- AppDelegate* delegate = (AppDelegate*)[UIApplication sharedApplication].delegate;
- delegate.allowAutoRotate = YES;
- [UIDevice switchNewOrientation:UIInterfaceOrientationLandscapeRight inController:self];
- }
- else {
- if (IS_IPAD) {
- self.zh_statusBarHidden = NO;
- }
- AppDelegate* delegate = (AppDelegate*)[UIApplication sharedApplication].delegate;
- delegate.allowAutoRotate = NO;
- [UIDevice switchNewOrientation:UIInterfaceOrientationPortrait inController:self];
- }
- }
- - (void)viewWillAppear:(BOOL)animated {
- [super viewWillAppear:animated];
- if (self.needReload) {
- self.needReload = NO;
- [self.myWebView reload];
- }
- if (_hasChangeSource) {
- [self setParmDic:self.parmDic];
- }
- if (self.isFirstLoad == NO) {
- [self sendResumeMessage];
- }
- self.isFirstLoad = NO;
-
- [self checkCaptured];
- }
- - (void)sendResumeMessage {
-
- NSMutableDictionary *parm = [NSMutableDictionary dictionary];
- [parm setValue:@"webViewOnResume" forKey:@"api"];
- [self postMessage:parm];
- }
- - (void)viewWillDisappear:(BOOL)animated {
- [super viewWillDisappear:animated];
- BOOL isBack = [self isViewPopDismiss];
- if (isBack) {
- if (self.preCtrl) {
- if (self.ks_landScape != self.preCtrl.ks_landScape) {
- [self changeOrientation:self.preCtrl.ks_landScape];
- }
- }
- if (![self.preCtrl isKindOfClass:[KSBaseWKWebViewController class]]) {
- [[UIApplication sharedApplication] setIdleTimerDisabled:NO];
- }
- }
- else {
- if ([self.presentedViewController isKindOfClass:NSClassFromString(@"TZImagePickerController")] || [self.presentedViewController isKindOfClass:NSClassFromString(@"RSKImageCropViewController")] || [self.presentedViewController isKindOfClass:NSClassFromString(@"KSVideoCropViewController")]) {
- NSLog(@"-----");
- }
- else {
- KSBaseViewController *nextCtrl = [self getNextViewController];
- if (nextCtrl) {
- if (nextCtrl.ks_landScape != self.ks_landScape) {
- [self changeOrientation:NO];
- }
- }
- }
- }
- }
- - (void)initWebView {
- [self.scrollView removeFromSuperview];
-
- if (_myWebView == nil) {
-
- WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
- config.selectionGranularity = WKSelectionGranularityDynamic;
- config.allowsInlineMediaPlayback = YES;
- config.mediaTypesRequiringUserActionForPlayback = NO;
- config.processPool = [KSBaseWKWebViewController singleWkProcessPool];
- config.websiteDataStore = [WKWebsiteDataStore defaultDataStore];
- [self configUserAgent:config];
- //自定义的WKScriptMessageHandler 是为了解决内存不释放的问题
- WeakWebViewScriptMessageDelegate *weakScriptMessageDelegate = [[WeakWebViewScriptMessageDelegate alloc] initWithDelegate:self];
- //这个类主要用来做native与JavaScript的交互管理
- WKUserContentController * wkUController = [[WKUserContentController alloc] init];
- [wkUController addScriptMessageHandler:weakScriptMessageDelegate name:SCRIPT_NAME];
- config.userContentController = wkUController;
-
- WKPreferences *preferences = [WKPreferences new];
- // 是否支出javaScript
- preferences.javaScriptEnabled = YES;
- //不通过用户交互,是否可以打开窗口
- preferences.javaScriptCanOpenWindowsAutomatically = YES;
- config.preferences = preferences;
- _myWebView = [[WKWebView alloc] initWithFrame:CGRectZero configuration:config];
- _myWebView.UIDelegate = self;
- _myWebView.navigationDelegate = self;
- _myWebView.scrollView.bounces = NO;
- _myWebView.scrollView.showsVerticalScrollIndicator = NO;
- _myWebView.scrollView.showsHorizontalScrollIndicator = NO;
- // _myWebView.allowsBackForwardNavigationGestures = YES;
- [self.view addSubview:_myWebView];
- #ifdef DEBUG
- if (@available(iOS 16.4, *)) {
- _myWebView.inspectable = YES;
- }
- #endif
- // 加载进度条和title
- [_myWebView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
- [_myWebView addObserver:self forKeyPath:@"title" options:NSKeyValueObservingOptionNew context:NULL];
- [self.view addSubview:_myWebView];
- [_myWebView mas_makeConstraints:^(MASConstraintMaker *make) {
- make.left.right.mas_equalTo(self.view);
- make.top.mas_equalTo(self.view.mas_top);
- make.bottom.mas_equalTo(self.view.mas_bottom);
- }];
- _myWebView.scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
- [self setupProgress];
- // 修改userAgent
- [self loadRequest];
- }
- else {
- [_myWebView reload];
- }
- }
- - (void)configUserAgent:(WKWebViewConfiguration *)config {
- NSString *oldUserAgent = config.applicationNameForUserAgent;
- NSString *newAgent = [NSString stringWithFormat:@"%@ %@ %@",oldUserAgent,AGENT_NAME,AGENT_DOMAIN];
- config.applicationNameForUserAgent = newAgent;
- }
- - (void)loadRequest {
-
- NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:self.url] cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:60.0f];
- [self.myWebView loadRequest:request];
- }
- - (NSString *)url {
- if (_url) {
- if ([_url containsString:@"Authorization="]) {
- NSRange range = [_url rangeOfString:@"Authorization="];
- if (range.location != NSNotFound) {
- _url = [_url substringToIndex:range.location-1];
- }
- }
- NSString *sepectString = [_url containsString:@"?"] ? @"&" : @"?";
- NSString *tokenStr = UserDefault(TokenKey);
- if (![NSString isEmptyString:tokenStr]) {
- NSString *token = [[NSString stringWithFormat:@"Authorization=%@ %@", UserDefault(Token_type), tokenStr] stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
- _url = [NSString stringWithFormat:@"%@%@%@",_url, sepectString, token];
- }
- }
- return _url;
- }
- #pragma mark --- 返回按钮的处理
- - (void)backPreViewAction {
- [self.myWebView stopLoading];
- if (_backRootView) {
- [self.navigationController popToRootViewControllerAnimated:NO];
- return;
- }
- else if (_isBackPreView) {
- [self.navigationController popViewControllerAnimated:YES];
- return;
- }
- else {
- [self.navigationController popViewControllerAnimated:YES];
- }
- }
- - (void)backAction {
- [self.myWebView stopLoading];
- if (_backRootView) {
- [self.navigationController popToRootViewControllerAnimated:NO];
- return;
- }
- else if (_isBackPreView) {
- [self.navigationController popViewControllerAnimated:YES];
- return;
- }
- else if ([self.myWebView canGoBack]) {
- [self.myWebView goBack];
- }
- else {
- [self.navigationController popViewControllerAnimated:YES];
- }
- }
- #pragma mark - WKScriptMessageHandler
- - (void)userContentController:(WKUserContentController *)userContentController
- didReceiveScriptMessage:(WKScriptMessage *)message {
- if ([message.name isEqualToString:SCRIPT_NAME]) {
- NSDictionary *parm = [self convertJsonStringToNSDictionary:message.body];
- // 回到主线程
- dispatch_async(dispatch_get_main_queue(), ^{
- [self handleScriptMessageSource:parm];
- });
- }
- }
- - (void)handleScriptMessageSource:(NSDictionary *)parm {
- if ([[parm ks_stringValueForKey:@"api"] isEqualToString:@"back"]) { // 返回
- [self backPreViewAction];
- }
- else if ([[parm ks_stringValueForKey:@"api"] isEqualToString:@"goBack"]) { // 逐级返回
- [self backAction];
- }
- else if ([[parm ks_stringValueForKey:@"api"] isEqualToString:@"login"]) {
- // 回到登录页面
- [self backLoginView];
- }
- else if ([[parm ks_stringValueForKey:@"api"] isEqualToString:@"openWebView"]) { // 打开新页面
- NSDictionary *valueDic = [parm ks_dictionaryValueForKey:@"content"];
-
- KSBaseWKWebViewController *detailCtrl = [[KSBaseWKWebViewController alloc] init];
- detailCtrl.url = [valueDic ks_stringValueForKey:@"url"];
- detailCtrl.parmDic = valueDic;
- NSInteger orientation = [valueDic ks_integerValueForKey:@"orientation"];
- BOOL isLandScape = orientation == 0 ? YES : NO;
- detailCtrl.ks_landScape = isLandScape;
- [self postMessage:parm];
- [self.navigationController pushViewController:detailCtrl animated:YES];
- }
- else if ([[parm ks_stringValueForKey:@"api"] isEqualToString:@"setRequestedOrientation"]) {
- NSDictionary *valueDic = [parm ks_dictionaryValueForKey:@"content"];
- // 横竖屏
- NSInteger orientation = [valueDic ks_integerValueForKey:@"orientation"];
- BOOL isLandScape = orientation == 0 ? YES : NO;
- self.ks_landScape = isLandScape;
- [self changeOrientation:isLandScape];
-
- }
- else if ([[parm ks_stringValueForKey:@"api"] isEqualToString:@"keepScreenLongLight"]) {
- NSDictionary *valueDic = [parm ks_dictionaryValueForKey:@"content"];
- BOOL isOpenLight = [valueDic ks_boolValueForKey:@"isOpenLight"];
- [[UIApplication sharedApplication] setIdleTimerDisabled:isOpenLight];
- }
- else if ([[parm ks_stringValueForKey:@"api"] isEqualToString:@"downLoad"]) {
- NSDictionary *valueDic = [parm ks_dictionaryValueForKey:@"content"];
- if ([valueDic ks_stringValueForKey:@"PDF"]) {
- NSString *url = [valueDic ks_stringValueForKey:@"downloadUrl"];
- [KSNetworkingManager downloadFileRequestWithFileUrl:url progress:^(int64_t bytesRead, int64_t totalBytes) {
- } success:^(NSURL * _Nonnull fileUrl) {
- [LOADING_MANAGER KSShowMsg:@"下载成功" promptCompletion:^{
- [self displaySource:fileUrl];
- }];
- } faliure:^(NSError * _Nonnull error) {
- }];
- }
- }
- // 回调是否刘海屏
- else if ([[parm ks_stringValueForKey:@"api"] isEqualToString:@"isSpecialShapedScreen"]) {
- BOOL isShapedScreen = iPhoneXSafeTopMargin > 0 ? YES : NO;
- NSMutableDictionary *valueDic = [NSMutableDictionary dictionaryWithDictionary:[parm ks_dictionaryValueForKey:@"content"]];
- [valueDic setValue:@(isShapedScreen) forKey:@"isSpecialShapedScreen"];
- [valueDic setValue:@(iPhoneXSafeTopMargin*2) forKey:@"notchHeight"];
- NSMutableDictionary *sendParm = [NSMutableDictionary dictionaryWithDictionary:parm];
- [sendParm setValue:valueDic forKey:@"content"];
- [self postMessage:sendParm];
- }
- else if ([[parm ks_stringValueForKey:@"api"] isEqualToString:@"getToken"]) {
- NSMutableDictionary *valueDic = [NSMutableDictionary dictionaryWithDictionary:[parm ks_dictionaryValueForKey:@"content"]];
- [valueDic setValue:UserDefault(Token_type) forKey:@"tokenType"];
- [valueDic setValue:UserDefault(TokenKey) forKey:@"accessToken"];
- NSMutableDictionary *sendParm = [NSMutableDictionary dictionaryWithDictionary:parm];
- [sendParm setValue:valueDic forKey:@"content"];
- [self postMessage:sendParm];
- }
-
- else if ([[parm ks_stringValueForKey:@"api"] isEqualToString:@"openAccompanyWebView"]) { // 打开伴奏
- [RecordCheckManager checkCameraPremissionAvaiableCallback:^(PREMISSIONTYPE type) {
- [self afterCheckCameraCheckMic:type parm:parm];
- }];
- }
- else if ([[parm ks_stringValueForKey:@"api"] isEqualToString:@"checkAlbum"]) { // 判断权限
- [RecordCheckManager checkPhotoLibraryPremissionAvaiableCallback:^(PREMISSIONTYPE type) {
- if (type == PREMISSIONTYPE_YES) {
- [self postMessage:parm];
- }
- else {
- [self showAlertWithMessage:@"请开启相册访问权限" type:CHECKDEVICETYPE_CAMREA];
- }
- }];
- }
- else if ([[parm ks_stringValueForKey:@"api"] isEqualToString:@"shareAchievements"]) { // 分享
- //
- [self shareFunctionWithParm:parm];
- }
- else if ([[parm ks_stringValueForKey:@"api"] isEqualToString:@"setStatusBarTextColor"]) { // 设置状态栏颜色
- NSDictionary *valueDic = [parm ks_dictionaryValueForKey:@"content"];
- BOOL whiteColor = [valueDic ks_boolValueForKey:@"statusBarTextColor"];
- if (whiteColor) {
- [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
- }
- else {
- if (@available(iOS 13.0, *)) {
- [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleDarkContent;
- } else {
- // Fallback on earlier versions
- [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleDefault;
- }
- }
- }
- else if ([[parm ks_stringValueForKey:@"api"] isEqualToString:@"getNavHeight"]) { // 获取状态栏高度和 title heigt
- NSDictionary *valueDic = [parm ks_dictionaryValueForKey:@"content"];
- [valueDic setValue:[NSNumber numberWithFloat:STATUS_GAP*2] forKey:@"navHeight"];
- [valueDic setValue:@(44*2) forKey:@"titleHeight"];
- [parm setValue:valueDic forKey:@"content"];
- [self postMessage:parm];
- }
-
- else if ([[parm ks_stringValueForKey:@"api"] isEqualToString:@"joinChatGroup"]) {
- NSDictionary *valueDic = [parm ks_dictionaryValueForKey:@"content"];
- NSString *targetId = [valueDic ks_stringValueForKey:@"id"];
- if ([[valueDic ks_stringValueForKey:@"type"] isEqualToString:@"single"]) { // 单聊
-
- TUIChatConversationModel *model = [[TUIChatConversationModel alloc] init];
- model.userID = targetId;
- KSChatConversationViewController *ctrl = [[KSChatConversationViewController alloc] init];
- ctrl.conversation = model;
- [self.navigationController pushViewController:ctrl animated:YES];
- }
- else if ([[valueDic ks_stringValueForKey:@"type"] isEqualToString:@"multi"]) { // 群聊
- if ([NSString isEmptyString:targetId]) {
- [LOADING_MANAGER MBShowAUTOHidingInWindow:@"报名未结束,暂无群组"];
- return;
- }
- TUIChatConversationModel *model = [[TUIChatConversationModel alloc] init];
- model.groupID = targetId;
- KSGroupConversationController *ctrl = [[KSGroupConversationController alloc] init];
- ctrl.conversation = model;
- [self.navigationController pushViewController:ctrl animated:YES];
- }
- }
- else if ([[parm ks_stringValueForKey:@"api"] isEqualToString:@"chooseFile"]) {
- NSDictionary *valueDic = [parm ks_dictionaryValueForKey:@"content"];
- self.chooseFileParm = [NSMutableDictionary dictionaryWithDictionary:valueDic];
- NSString *typeStr = [valueDic ks_stringValueForKey:@"type"];
- NSInteger maxCount = [valueDic ks_integerValueForKey:@"max"];
- NSString *bucket = [valueDic ks_stringValueForKey:@"bucket"];
- [self chooseFileWithType:typeStr maxNumber:maxCount bucket:bucket];
- }
- else if ([[parm ks_stringValueForKey:@"api"] isEqualToString:@"setAddress"]) { // 跳转地址选择
- AddressListViewController *ctrl = [[AddressListViewController alloc] init];
- ctrl.isChooseAddress = YES;
- MJWeakSelf;
- [ctrl chooseAddressAction:^(AddressListModel * _Nonnull model) {
- [weakSelf sendAddressAction:model];
- }];
- [self.navigationController pushViewController:ctrl animated:YES];
- }
- else if ([[parm ks_stringValueForKey:@"api"] isEqualToString:@"savePicture"]) { // 保存图片到相册
- // 判断相册权限
- [RecordCheckManager checkPhotoLibraryPremissionAvaiableCallback:^(PREMISSIONTYPE type) {
- if (type == PREMISSIONTYPE_YES) {
- NSDictionary *valueDic = [parm ks_dictionaryValueForKey:@"content"];
- NSString *base64String = [valueDic ks_stringValueForKey:@"base64"];
- UIImage *saveImage = [self imageWithBase64String:base64String];
- [[TZImageManager manager] savePhotoWithImage:saveImage completion:^(PHAsset *asset, NSError *error) {
- if (!error) {
- [self savePicCallback:[valueDic ks_stringValueForKey:@"uuid"] isSuccess:YES];
- }
- else {
- [self savePicCallback:[valueDic ks_stringValueForKey:@"uuid"] isSuccess:NO];
- }
- }];
- }
- else {
- [self showAlertWithMessage:@"请开启相册访问权限" type:CHECKDEVICETYPE_CAMREA];
- }
- }];
- }
- else if ([[parm ks_stringValueForKey:@"api"] isEqualToString:@"getVersion"]) {
- NSDictionary *valueDic = [parm ks_dictionaryValueForKey:@"content"];
- NSMutableDictionary *sendParm = [NSMutableDictionary dictionary];
- [parm setValue:@"getVersion" forKey:@"api"];
- NSMutableDictionary *content = [NSMutableDictionary dictionary];
- [content setValue:[USER_MANAGER getCurrentVersion] forKey:@"version"];
- [content setValue:[valueDic ks_stringValueForKey:@"uuid"] forKey:@"uuid"];
- [sendParm setValue:content forKey:@"content"];
- [self postMessage:sendParm];
- }
- else if ([[parm ks_stringValueForKey:@"api"] isEqualToString:@"getDeviceStatus"]) {
- NSDictionary *valueDic = [parm ks_dictionaryValueForKey:@"content"];
- NSString *type = [valueDic ks_stringValueForKey:@"type"];
- if ([type isEqualToString:@"video"]) {
- dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
- NSString *status;
- if ([self checkIsCaptured]) {
- status = @"1";
- }
- else {
- status = @"0";
- }
- NSMutableDictionary *sendParm = [NSMutableDictionary dictionary];
- [sendParm setValue:@"getDeviceStatus" forKey:@"api"];
- NSMutableDictionary *content = [NSMutableDictionary dictionary];
- [content setValue:[valueDic ks_stringValueForKey:@"type"] forKey:@"type"];
- [content setValue:[valueDic ks_stringValueForKey:@"uuid"] forKey:@"uuid"];
- [content setValue:status forKey:@"status"];
- [sendParm setValue:content forKey:@"content"];
- [self postMessage:sendParm];
- });
- }
- }
- else if ([[parm ks_stringValueForKey:@"api"] isEqualToString:@"callPhone"]) {
- NSDictionary *valueDic = [parm ks_dictionaryValueForKey:@"content"];
- NSString *phone = [valueDic ks_stringValueForKey:@"phone"];
- [self CallPhoneWith:phone];
- }
- else if ([[parm ks_stringValueForKey:@"api"] isEqualToString:@"setCache"]) {
- NSDictionary *valueDic = [parm ks_dictionaryValueForKey:@"content"];
- NSString *key = [valueDic ks_stringValueForKey:@"key"];
- NSString *value = [valueDic ks_stringValueForKey:@"value"];
- UserDefaultSetObjectForKey(value, key);
- }
- else if ([[parm ks_stringValueForKey:@"api"] isEqualToString:@"getCache"]) {
- NSDictionary *valueDic = [parm ks_dictionaryValueForKey:@"content"];
- NSString *key = [valueDic ks_stringValueForKey:@"key"];
- NSString *value = UserDefault(key);
-
- NSMutableDictionary *parm = [NSMutableDictionary dictionaryWithDictionary:valueDic];
- [parm setValue:value forKey:@"value"];
- NSMutableDictionary *sendParm = [NSMutableDictionary dictionary];
- [sendParm setValue:@"getCache" forKey:@"api"];
- [sendParm setValue:parm forKey:@"content"];
- [self postMessage:sendParm];
- }
- else if ([[parm ks_stringValueForKey:@"api"] isEqualToString:@"isInstall"]) {
- NSDictionary *valueDic = [parm ks_dictionaryValueForKey:@"content"];
- NSString *type = [valueDic ks_stringValueForKey:@"type"];
-
- NSURL *url = [NSURL URLWithString:type];
- BOOL canOpen = [[UIApplication sharedApplication] canOpenURL:url];
- NSInteger installStatus = canOpen ? 1 : 0;
-
- NSMutableDictionary *parm = [NSMutableDictionary dictionaryWithDictionary:valueDic];
- [parm setValue:@(installStatus) forKey:@"installStatus"];
- NSMutableDictionary *sendParm = [NSMutableDictionary dictionary];
- [sendParm setValue:@"isInstall" forKey:@"api"];
- [sendParm setValue:parm forKey:@"content"];
- [self postMessage:sendParm];
- }
- else if ([[parm ks_stringValueForKey:@"api"] isEqualToString:@"openApp"]) {
- NSDictionary *valueDic = [parm ks_dictionaryValueForKey:@"content"];
- NSString *type = [valueDic ks_stringValueForKey:@"type"];
-
- NSURL *url = [NSURL URLWithString:type];
- if ([[UIApplication sharedApplication] canOpenURL:url]) {
- [[UIApplication sharedApplication] openURL:url options:@{} completionHandler:nil];
- }
- }
-
- else if ([[parm ks_stringValueForKey:@"api"] isEqualToString:@"downloadApp"]) {
- NSDictionary *valueDic = [parm ks_dictionaryValueForKey:@"content"];
- NSString *openUrl = [valueDic ks_stringValueForKey:@"url"];
- bool can = [[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:openUrl]];
- if(can){
- [[UIApplication sharedApplication] openURL:[NSURL URLWithString:openUrl] options:@{} completionHandler:nil];
- }
- }
- else if ([[parm ks_stringValueForKey:@"api"] isEqualToString:@"shareTripartite"]) { // 分享到微信
- [self shareToWeChat:parm];
- }
- else if ([[parm ks_stringValueForKey:@"api"] isEqualToString:@"saveFile"]) { // 下载资源
- NSDictionary *content = [parm ks_dictionaryValueForKey:@"content"];
- NSString *url = [content ks_stringValueForKey:@"url"];
- [self downFile:url];
- }
- else if ([[parm ks_stringValueForKey:@"api"] isEqualToString:@"videoCrop"]) { // 选择封面
- NSDictionary *content = [parm ks_dictionaryValueForKey:@"content"];
- KSVideoCropViewController *ctrl = [[KSVideoCropViewController alloc] init];
- NSString *videoUrl = [content ks_stringValueForKey:@"url"];
- [ctrl configWithVideoRemoteUrl:videoUrl];
- [ctrl changeLandScape];
- MJWeakSelf;
- [ctrl chooseCropImageCallback:^(UIImage * _Nonnull cropImage) {
- [weakSelf videCropImage:cropImage content:content];
- }];
- ctrl.modalPresentationStyle = UIModalPresentationFullScreen;
- [self.navigationController presentViewController:ctrl animated:YES completion:nil];
- }
- else if ([[parm ks_stringValueForKey:@"api"] isEqualToString:@"paymentOrder"]) {
- NSDictionary *content = [parm ks_dictionaryValueForKey:@"content"];
- NSString *channel = [content ks_stringValueForKey:@"payChannel"];
- if ([channel isEqualToString:@"ali_app"]) {
- NSString *infoMessage = [content ks_stringValueForKey:@"payInfo"];
- [KSOrderManager dealWithAliSDK:infoMessage];
- }
- else if ([channel isEqualToString:@"wx_app"]) {
- NSString *infoMessage = [content ks_stringValueForKey:@"payInfo"];
- [KSOrderManager dealWithWXSDK:infoMessage];
- }
- }
- else if ([[parm ks_stringValueForKey:@"api"] isEqualToString:@"joinLiveRoom"]) { // 进入直播间
- NSDictionary *valueDic = [parm ks_dictionaryValueForKey:@"content"];
- NSString *roomId = [valueDic ks_stringValueForKey:@"roomId"];
- [LOADING_MANAGER showHUD];
- [KSEnterLiveroomManager joinLiveWithRoomId:roomId inController:(CustomNavViewController *)self.navigationController callback:^{
- [LOADING_MANAGER removeHUD];
- }];
- }
- else if ([[parm ks_stringValueForKey:@"api"] isEqualToString:@"setEventTracking"]) {
- NSString *type = [[parm ks_dictionaryValueForKey:@"content"] ks_stringValueForKey:@"type"];
- [USER_MANAGER sendUMEvent:type];
- }
- // 课件相关
- else if ([[parm ks_stringValueForKey:@"api"] isEqualToString:@"getCourseFilePath"]) { // 课件资源查询
- NSDictionary *valueDic = [parm ks_dictionaryValueForKey:@"content"];
- NSString *localPath = [COURSEWARE_MANAGER queryFileUrlWithParm:valueDic];
- BOOL isServiceStart = [AppDelegate shareAppDelegate].httpServer.isRunning;
- if (![NSString isEmptyString:localPath] && isServiceStart) {
- localPath = [[localPath componentsSeparatedByString:@"CoursewarePath/"] lastObject];
- localPath = [NSString stringWithFormat:@"%@%@/%@",@"http://localhost:",[AppDelegate shareAppDelegate].serverPort,localPath];
- NSMutableDictionary *contentParm = [NSMutableDictionary dictionaryWithDictionary:valueDic];
- [contentParm setValue:localPath forKey:@"localPath"];
- NSMutableDictionary *sendParm = [NSMutableDictionary dictionary];
- [sendParm setValue:@"getCourseFilePath" forKey:@"api"];
- [sendParm setValue:contentParm forKey:@"content"];
- [self postMessage:sendParm];
- }
- else {
- [self postMessage:parm];
- }
- }
- else if ([[parm ks_stringValueForKey:@"api"] isEqualToString:@"checkCoursewareCache"]) {
- MJWeakSelf;
- [COURSEWARE_MANAGER checkCourseCacheStatus:parm callback:^(NSDictionary * _Nonnull parm) {
- [weakSelf postMessage:parm];
- }];
- }
- else if ([[parm ks_stringValueForKey:@"api"] isEqualToString:@"downloadCoursewareToCache"]) {
- NSDictionary *valueDic = [parm ks_dictionaryValueForKey:@"content"];
- NSString *lessonCoursewareDetailId = [[valueDic ks_dictionaryValueForKey:@"data"] ks_stringValueForKey:@"lessonCoursewareDetailId"];
- if (COURSEWARE_MANAGER.isDownloading) {
- if ([lessonCoursewareDetailId isEqualToString:COURSEWARE_MANAGER.lessonCoursewareDetailId]) {
- [LOADING_MANAGER MBShowAUTOHidingInWindow:@"当前已有课件资源下载中"];
- [self downloadWithParm:parm];
- }
- else {
- [LOADING_MANAGER MBShowAUTOHidingInWindow:@"当前已有课件资源下载中"];
- NSMutableDictionary *contentParm = [NSMutableDictionary dictionary];
- [contentParm setValue:@(3) forKey:@"status"];
- [contentParm setValue:@(0) forKey:@"progress"];
- [contentParm setValue:lessonCoursewareDetailId forKey:@"lessonCoursewareDetailId"];
- NSMutableDictionary *sendParm = [NSMutableDictionary dictionary];
- [sendParm setValue:@"downloadCoursewareToCache" forKey:@"api"];
- [sendParm setValue:contentParm forKey:@"content"];
- [self postMessage:sendParm];
- }
- }
- else {
- if ([self isWiFiEnable] == NO) {
- self.wifiAlert = [KSNewAlertView shareInstance];
- MJWeakSelf;
- [self.wifiAlert configTitle:@"提示" descMessage:@"当前非Wi-Fi环境,是否开始下载?" leftButtonTitle:@"取消" rightButtonTitle:@"确认" leftButtonAction:^{
-
- } rightButtonAction:^{
- [weakSelf downloadWithParm:parm];
- }];
- [self.wifiAlert showAlert];
- }
- else {
- [self downloadWithParm:parm];
- }
- }
- }
- else if ([[parm ks_stringValueForKey:@"api"] isEqualToString:@"cancelDownloadCourseware"]) { // 取消下载课件
- if (COURSEWARE_MANAGER.isDownloading) { // 如果在下载 取消
- [COURSEWARE_MANAGER cancleDownloadCourseware];
- }
- NSMutableDictionary *content = [NSMutableDictionary dictionaryWithDictionary:[parm ks_dictionaryValueForKey:@"content"]];
- [content setValue:@(YES) forKey:@"status"];
- NSMutableDictionary *sendParm = [NSMutableDictionary dictionary];
- [sendParm setValue:@"cancelDownloadCourseware" forKey:@"api"];
- [sendParm setValue:content forKey:@"content"];
- [self postMessage:sendParm];
- }
-
- }
- - (void)afterCheckCameraCheckMic:(PREMISSIONTYPE)cameraType parm:(NSDictionary *)sourceParm {
-
- [RecordCheckManager checkMicPermissionAvaiableCallback:^(PREMISSIONTYPE type) {
- if (type == PREMISSIONTYPE_YES && cameraType == PREMISSIONTYPE_YES) {
- NSDictionary *valueDic = [sourceParm ks_dictionaryValueForKey:@"content"];
- KSAccompanyWebViewController *detailCtrl = [[KSAccompanyWebViewController alloc] init];
- detailCtrl.url = [valueDic ks_stringValueForKey:@"url"];
- detailCtrl.parmDic = valueDic;
- NSInteger orientation = [valueDic ks_integerValueForKey:@"orientation"];
- BOOL isLandScape = orientation == 0 ? YES : NO;
- detailCtrl.ks_landScape = isLandScape;
- [self postMessage:sourceParm];
- [self.navigationController pushViewController:detailCtrl animated:YES];
- }
- else { //
-
- NSString *content = @"";
- CHECKDEVICETYPE checkType = CHECKDEVICETYPE_BOTH;
- if (cameraType == PREMISSIONTYPE_NO && type == PREMISSIONTYPE_NO) {
- content = @"请开启相机和麦克风访问权限";
- checkType = CHECKDEVICETYPE_BOTH;
- }
- else if (cameraType == PREMISSIONTYPE_NO && type == PREMISSIONTYPE_YES) {
- content = @"请开启相机访问权限";
- checkType = CHECKDEVICETYPE_CAMREA;
- }
- else if (cameraType == PREMISSIONTYPE_YES && type == PREMISSIONTYPE_NO) {
- content = @"请开启麦克风访问权限";
- checkType = CHECKDEVICETYPE_MIC;
- }
- [self showAlertWithMessage:content type:checkType];
- }
- }];
- }
- - (void)downloadWithParm:(NSDictionary *)parm {
- MJWeakSelf;
- [COURSEWARE_MANAGER downloadCourseWithParm:parm callback:^(NSDictionary * _Nonnull sendParm) {
- [weakSelf postMessage:sendParm];
- }];
- }
- - (void)removeLoadHud {
- [LOADING_MANAGER removeCustomLoading];
- }
- - (void)videCropImage:(UIImage *)cover content:(NSDictionary *)content {
- NSData *imgData = [UIImage turnsImaegDataByImage:cover];
- NSString *fileName = @"videoCoverImage";
-
- [LOADING_MANAGER showCancelCustomLoading:@"上传中..." cancel:^{
- [UPLOAD_MANAGER cancelUploadCallback:^{
- [self removeLoadHud];
- }];
- }];
- [UPLOAD_MANAGER configWithfilePath:@"/user/"];
- [UPLOAD_MANAGER uploadFile:imgData fileName:fileName fileSuffix:[UIImage typeForImageData:imgData] progress:^(int64_t bytesWritten, int64_t totalBytes) {
- // 显示进度
- int progress = (int)(bytesWritten / totalBytes * 100);
- __block NSString *tipsMessage = [NSString stringWithFormat:@"上传中 %d%%",progress];
- dispatch_main_async_safe(^{
- [LOADING_MANAGER.loadingView setDisplayText:tipsMessage];
- });
- } successCallback:^(NSMutableArray * _Nonnull fileUrlArray) {
- [LOADING_MANAGER removeCustomLoading];
- NSString *fileUrl = [fileUrlArray lastObject];
- NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithDictionary:content];
- [dic setValue:fileUrl forKey:@"videoCover"];
- NSMutableDictionary *sendParm = [NSMutableDictionary dictionary];
- [sendParm setValue:@"videoCrop" forKey:@"api"];
- [sendParm setValue:dic forKey:@"content"];
- [self postMessage:sendParm];
- } faliure:^(NSError * _Nullable error, NSString * _Nullable descMessaeg) {
- [LOADING_MANAGER removeCustomLoading];
- }];
- }
- - (void)downFile:(NSString *)fileUrl {
- [LOADING_MANAGER showCustomLoading:@"文件下载中..."];
- [KSNetworkingManager downloadFileRequestWithFileUrl:fileUrl progress:^(int64_t bytesRead, int64_t totalBytes) {
-
- } success:^(NSURL * _Nonnull fileUrl) {
- [LOADING_MANAGER removeCustomLoading];
- [self saveFileWithUrl:fileUrl];
- } faliure:^(NSError * _Nonnull error) {
- [LOADING_MANAGER removeCustomLoading];
- [LOADING_MANAGER MBShowAUTOHidingInWindow:@"下载失败"];
- }];
- }
- - (void)saveFileWithUrl:(NSURL *)fileUrl {
- if ([fileUrl.absoluteString hasSuffix:@".mp4"]) { // 视频
- [RecordCheckManager checkPhotoLibraryPremissionAvaiableCallback:^(PREMISSIONTYPE type) {
- if (type == PREMISSIONTYPE_YES) {
- [self saveVideo:fileUrl];
- }
- else {
- [self showAlertWithMessage:@"请开启相册访问权限" type:CHECKDEVICETYPE_CAMREA];
- }
- }];
- }
- else { // 音频
- [self saveFileToPhone:fileUrl];
- }
- }
- - (void)saveVideo:(NSURL *)fileUrl {
- [LOADING_MANAGER showCustomLoading:@"视频保存中..."];
- [[TZImageManager manager] saveVideoWithUrl:fileUrl completion:^(PHAsset *asset, NSError *error) {
- if (!error) {
- dispatch_main_async_safe(^{
- [LOADING_MANAGER removeCustomLoading];
- [LOADING_MANAGER MBShowAUTOHidingInWindow:@"已保存到相册"];
- });
- }
- else {
- dispatch_main_async_safe(^{
- [LOADING_MANAGER removeCustomLoading];
- [LOADING_MANAGER MBShowAUTOHidingInWindow:@"保存视频错误"];
- });
- }
- }];
- }
- - (void)saveFileToPhone:(NSURL *)fileUrl {
- self.isDownloadFile = YES;
- UIDocumentPickerViewController *documentPicker = [[UIDocumentPickerViewController alloc] initWithURL:fileUrl inMode:UIDocumentPickerModeExportToService];
- documentPicker.delegate = self;
- documentPicker.modalPresentationStyle = UIModalPresentationFormSheet;
- [self presentViewController:documentPicker animated:YES completion:nil];
- }
- - (void)chooseFileWithType:(NSString *)typeStr maxNumber:(NSInteger)maxCount bucket:(NSString *)bucket {
- if ([typeStr isEqualToString:@"img"]) { // 选择图片上传
- if (maxCount > 9) {
- maxCount = 9;
- }
- [self chooseMediaWithType:MEDIATYPE_PHOTO maxCount:maxCount bucket:bucket];
- }
- else if ([typeStr isEqualToString:@"video"]) {
- [self chooseMediaWithType:MEDIATYPE_VIDEO maxCount:1 bucket:bucket];
- }
- else if ([typeStr isEqualToString:@"file"]) {
- [self chooseDocumentWithType:CHOOSETYPE_ALL bucket:bucket];
- }
- else if ([typeStr isEqualToString:@"midi"]) {
- [self chooseDocumentWithType:CHOOSETYPE_MIDI bucket:bucket];
- }
- else if ([typeStr isEqualToString:@"mp3"]) {
- [self chooseDocumentWithType:CHOOSETYPE_MP3 bucket:bucket];
- }
- else if (([typeStr isEqualToString:@"xml"] || [typeStr isEqualToString:@"musicxml"])) {
- [self chooseDocumentWithType:CHOOSETYPE_XML bucket:bucket];
- }
- }
- - (void)chooseDocumentWithType:(CHOOSETYPE)fileTyle bucket:(NSString *)bucket {
- self.bucketName = bucket;
- self.fileChooseType = fileTyle;
- NSArray *documentTypes = @[@"public.content", @"public.text", @"public.source-code", @"public.image", @"public.audio", @"public.audiovisual-content", @"com.adobe.pdf", @"com.apple.keynote.key", @"com.microsoft.word.doc", @"com.microsoft.excel.xls", @"com.microsoft.powerpoint.ppt"];
- KSDocumentViewController *documentPickerViewController = [[KSDocumentViewController alloc] initWithDocumentTypes:documentTypes inMode:UIDocumentPickerModeImport];
- documentPickerViewController.delegate = self;
- documentPickerViewController.modalPresentationStyle = UIModalPresentationFullScreen;
- [self presentViewController:documentPickerViewController animated:YES completion:nil];
- }
- - (void)chooseMediaWithType:(MEDIATYPE)type maxCount:(NSInteger)maxCount bucket:(NSString *)bucketName {
- self.mediaManager = [[KSMediaManager alloc] init];
- self.mediaManager.mediaType = type;
- self.mediaManager.maxPhotoNumber = maxCount;
- self.mediaManager.baseCtrl = self;
- self.mediaManager.needCropImage = NO;
- self.mediaManager.videoMaxDuration = 40 * 60;
- MJWeakSelf;
- [self.mediaManager noAlertCallback:^(NSString * _Nullable videoUrl, NSMutableArray * _Nullable imageArray, NSMutableArray * _Nullable imageAsset) {
-
- if (type == MEDIATYPE_PHOTO) {
- [weakSelf uploadImageArray:imageArray bucket:bucketName];
- }
- else {
- NSLog(@"%@", videoUrl);
- // 上传视频
- [weakSelf uploadVideoWithUrl:videoUrl bucket:bucketName];
- }
-
- }];
- [self.mediaManager pushImagePickerController];
- }
- - (void)savePicCallback:(NSString *)uuid isSuccess:(BOOL)isSuccess {
- NSString *status = isSuccess ? @"success" : @"fail";
- NSMutableDictionary *parm = [NSMutableDictionary dictionary];
- [parm setValue:@"savePicture" forKey:@"api"];
- NSMutableDictionary *content = [NSMutableDictionary dictionary];
- [content setValue:status forKey:@"status"];
- [content setValue:uuid forKey:@"uuid"];
- [parm setValue:content forKey:@"content"];
- [self postMessage:parm];
- }
- - (void)sendAddressAction:(AddressListModel *)model {
- NSMutableDictionary *sendParm = [NSMutableDictionary dictionary];
- [sendParm setValue:@"getAddress" forKey:@"api"];
- NSMutableDictionary *content = [NSMutableDictionary dictionary];
- [content setValue:model.internalBaseClassIdentifier forKey:@"id"];
- [content setValue:model.detailAddress forKey:@"detailAddress"];
- [content setValue:model.city forKey:@"city"];
- [content setValue:model.region forKey:@"region"];
- [content setValue:model.province forKey:@"province"];
- [content setValue:model.name forKey:@"name"];
- [content setValue:model.phoneNumber forKey:@"phoneNumber"];
- [content setValue:model.postCode forKey:@"postCode"];
- [sendParm setValue:content forKey:@"content"];
- [self postMessage:sendParm];
- }
- - (UIImage *)imageWithBase64String:(NSString *)base64String {
- NSURL *URL = [NSURL URLWithString:base64String];
- NSData *imageData = [NSData dataWithContentsOfURL:URL];
- UIImage *image = [UIImage imageWithData:imageData scale:2];
- return image;
- }
- - (void)shareFunctionWithParm:(NSDictionary *)parm {
-
- NSDictionary *content = [parm ks_dictionaryValueForKey:@"content"];
- NSString *typeString = [content ks_stringValueForKey:@"type"];
- KSSHARETYPE shareType = [typeString isEqualToString:@"image"] ? KSSHARETYPE_IMAGE : KSSHARETYPE_VODEO;
- NSString *shareTitle = [content ks_stringValueForKey:@"title"];
- NSString *descMessage = [content ks_stringValueForKey:@"desc"];
- NSString *videoUrl = [content ks_stringValueForKey:@"video"];
- NSString *saveLinkUrl = [content ks_stringValueForKey:@"url"];
- NSString *imgStr = [content ks_stringValueForKey:@"image"];
- UIImage *shareImage = [self imageWithBase64String:imgStr];
- NSArray *buttonArray = [content ks_arrayValueForKey:@"button"];
- BOOL containCopyButton = NO;
- for (NSString *nameString in buttonArray) {
- if ([nameString isEqualToString:@"copy"]) {
- containCopyButton = YES;
- break;
- }
- }
-
- MJWeakSelf;
- self.shareManager = [KSUMShareManager shareInstanceShowWithImage:shareImage showSaveLink:containCopyButton saveLinkUrl:saveLinkUrl url:videoUrl shareTitle:shareTitle descMessage:descMessage shareType:shareType showInView:self callback:^(BOOL isSuccess, NSString * _Nonnull descMessage) {
- NSMutableDictionary *responParm = [NSMutableDictionary dictionary];
- [responParm setValue:[parm ks_stringValueForKey:@"api"] forKey:@"api"];
- NSMutableDictionary *content = [NSMutableDictionary dictionary];
- [content setValue:[content ks_stringValueForKey:@"UUID"] forKey:@"content"];
- [content setValue:descMessage forKey:@"message"];
- BOOL status = isSuccess;
- [content setValue:[NSNumber numberWithBool:status] forKey:@"status"];
- [responParm setValue:content forKey:@"content"];
- [weakSelf postMessage:responParm];
- }];
- }
- - (KSSHARETYPE)getTypeWithTypeString:(NSString *)typeString {
- if ([typeString isEqualToString:@"image"]) { // 图片
- return KSSHARETYPE_IMAGE;
- }
- else if ([typeString isEqualToString:@"link"]) { // 链接
- return KSSHARETYPE_URL;
- }
- else {
- return KSSHARETYPE_VODEO;
- }
- }
- - (void)shareToWeChat:(NSDictionary *)parm {
-
- NSDictionary *content = [parm ks_dictionaryValueForKey:@"content"];
- if ([[content ks_stringValueForKey:@"shareType"] isEqualToString:@"wechat"]) {
- NSString *typeString = [content ks_stringValueForKey:@"type"];
- KSSHARETYPE shareType = [self getTypeWithTypeString:typeString];
- NSString *shareTitle = [content ks_stringValueForKey:@"title"];
- NSString *descMessage = [content ks_stringValueForKey:@"desc"];
- NSString *url = [content ks_stringValueForKey:@"video"];
- if (shareType == KSSHARETYPE_URL) {
- url = [content ks_stringValueForKey:@"url"];
- }
- NSString *imgStr = [content ks_stringValueForKey:@"image"];
- UIImage *shareImage = [self imageWithBase64String:imgStr];
- NSString *thumImage = [content ks_stringValueForKey:@"thumb"];
-
- MJWeakSelf;
- self.shareManager = [KSUMShareManager shareInstanceToWechatWithImage:shareImage url:url shareTitle:shareTitle descMessage:descMessage shareType:shareType thumImage:thumImage callback:^(BOOL isSuccess, NSString * _Nonnull descMessage) {
- NSMutableDictionary *responParm = [NSMutableDictionary dictionary];
- [responParm setValue:[parm ks_stringValueForKey:@"api"] forKey:@"api"];
- NSMutableDictionary *content = [NSMutableDictionary dictionary];
- [content setValue:[content ks_stringValueForKey:@"UUID"] forKey:@"content"];
- [content setValue:descMessage forKey:@"message"];
- BOOL status = isSuccess;
- [content setValue:[NSNumber numberWithBool:status] forKey:@"status"];
- [responParm setValue:content forKey:@"content"];
- [weakSelf postMessage:responParm];
- }];
- }
- else if ([[content ks_stringValueForKey:@"shareType"] isEqualToString:@"wechat_circle"]) { // 微信朋友圈
- NSString *typeString = [content ks_stringValueForKey:@"type"];
- KSSHARETYPE shareType = [self getTypeWithTypeString:typeString];
- NSString *shareTitle = [content ks_stringValueForKey:@"title"];
- NSString *descMessage = [content ks_stringValueForKey:@"desc"];
- NSString *url = [content ks_stringValueForKey:@"video"];
- if (shareType == KSSHARETYPE_URL) {
- url = [content ks_stringValueForKey:@"url"];
- }
- NSString *imgStr = [content ks_stringValueForKey:@"image"];
- UIImage *shareImage = [self imageWithBase64String:imgStr];
- NSString *thumImage = [content ks_stringValueForKey:@"thumb"];
- MJWeakSelf;
- self.shareManager = [KSUMShareManager shareInstanceToWechatCircleWithImage:shareImage url:url shareTitle:shareTitle descMessage:descMessage shareType:shareType thumImage:thumImage callback:^(BOOL isSuccess, NSString * _Nonnull descMessage) {
- NSMutableDictionary *responParm = [NSMutableDictionary dictionary];
- [responParm setValue:[parm ks_stringValueForKey:@"api"] forKey:@"api"];
- NSMutableDictionary *content = [NSMutableDictionary dictionary];
- [content setValue:[content ks_stringValueForKey:@"UUID"] forKey:@"content"];
- [content setValue:descMessage forKey:@"message"];
- BOOL status = isSuccess;
- [content setValue:[NSNumber numberWithBool:status] forKey:@"status"];
- [responParm setValue:content forKey:@"content"];
- [weakSelf postMessage:responParm];
- }];
- }
- }
- - (void)showAlertWithMessage:(NSString *)message type:(CHECKDEVICETYPE)deviceType {
- [KSPremissionAlert shareInstanceDisplayImage:deviceType message:message showInView:self.view cancel:^{
-
- } confirm:^{
- [self openSettingView];
- }];
-
- }
- - (void)openSettingView {
- [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString] options:@{} completionHandler:nil];
- }
- - (void)displaySource:(NSURL *)localUrl {
- KSLocalWebViewController *ctrl = [[KSLocalWebViewController alloc] init];
- ctrl.headTitle = @"协议文件";
- ctrl.sourceData = [NSData dataWithContentsOfURL:localUrl];
- ctrl.fileUrl = localUrl;
- [self.navigationController pushViewController:ctrl animated:YES];
- }
- - (void)postMessage:(NSDictionary *)parm {
- NSLog(@"------ parm %@", [parm mj_JSONString]);
- if (_myWebView) {
- dispatch_async(dispatch_get_main_queue(), ^{
- NSString *jsString = [parm mj_JSONString];
- [self.myWebView evaluateJavaScript:[NSString stringWithFormat:@"postMessage(%@,'*')", jsString] completionHandler:nil];
- });
- }
- }
- // 刷新
- - (void)refreshUrl:(NSString *)refreshUrl {
-
- NSString *sepectString = [refreshUrl containsString:@"?"] ? @"&" : @"?";
- NSString *tokenStr = UserDefault(TokenKey);
- if (![NSString isEmptyString:tokenStr]) {
- NSString *token = [[NSString stringWithFormat:@"Authorization=%@ %@", UserDefault(Token_type), tokenStr] stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
- refreshUrl = [NSString stringWithFormat:@"%@%@%@",refreshUrl, sepectString, token];
- }
- NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:refreshUrl] cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:60.0f];
- [self.myWebView loadRequest:request];
- }
- // 返回登录页面
- - (void)backLoginView {
-
- NSString *webUrl = [self.url copy];
- if ([webUrl containsString:@"Authorization="]) {
- NSRange range = [webUrl rangeOfString:@"Authorization="];
- if (range.location != NSNotFound) {
- webUrl = [webUrl substringToIndex:range.location-1];
- }
- }
-
- // 获取次数
- NSString *failCount = UserDefault(@"WEB_FAILCOUNT");
- if ([NSString isEmptyString:failCount]) {
- failCount = @"1";
- UserDefaultSetObjectForKey(failCount, @"WEB_FAILCOUNT");
- UserDefaultSetObjectForKey(webUrl, WEB_URL);
- }
- else if (failCount.integerValue == 1) {
-
- NSString *preUrl = UserDefaultObjectForKey(FAIL_WEB_URL);
- if (![webUrl isEqualToString:preUrl]) { // 如果打开和之前失败不相同重新统计数据
- UserDefaultSetObjectForKey(@"1", @"WEB_FAILCOUNT");
- UserDefaultSetObjectForKey(webUrl, WEB_URL);
- }
- else {
- UserDefaultRemoveObjectForKey(@"WEB_FAILCOUNT");
- }
- }
- else {
- UserDefaultRemoveObjectForKey(@"WEB_FAILCOUNT");
- }
- // 当前失败的H5地址
- UserDefaultSetObjectForKey(webUrl, FAIL_WEB_URL);
-
- // 退出登录
- [APPLOGIN_MANAGER logoutActionWithMsg:@""];
- }
-
- #pragma mark ----- WKWebView delegate
- // 1 在发送请求之前,决定是否跳转
- - (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
- NSLog(@"1-------在发送请求之前,决定是否跳转 -->%@",navigationAction.request);
- NSURL *url = navigationAction.request.URL;
- NSString *scheme = [url scheme];
- UIApplication *app = [UIApplication sharedApplication];
- NSString *urlString = url.absoluteString;
- if (![urlString containsString:@"colexiu.com"] && ![urlString containsString:WEBHOST]) { // 外部链接
- self.isOutLink = YES;
- }
- else {
- self.isOutLink = NO;
- }
- // 打电话
- if ([scheme isEqualToString:@"tel"]) {
- if ([app canOpenURL:url]) {
- [app openURL:url];
- // 一定要加上这句,否则会打开新页面
- decisionHandler(WKNavigationActionPolicyCancel);
- return;
- }
- }
-
- decisionHandler(WKNavigationActionPolicyAllow);
- }
- // 2 页面开始加载时调用
- - (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation {
- NSLog(@"2-------页面开始加载时调用");
- }
- // 3 在收到响应后,决定是否跳转
- - (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler {
- /// 在收到服务器的响应头,根据response相关信息,决定是否跳转。decisionHandler必须调用,来决定是否跳转,参数WKNavigationActionPolicyCancel取消跳转,WKNavigationActionPolicyAllow允许跳转
- NSLog(@"3-------在收到响应后,决定是否跳转");
- decisionHandler(WKNavigationResponsePolicyAllow);
- }
- // 4 当内容开始返回时调用
- - (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation {
- NSLog(@"4-------当内容开始返回时调用");
- }
- // 5 页面加载完成之后调用
- - (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
- NSLog(@"5-------页面加载完成之后调用");
- if (_hasModify == NO) {
- [self configLocalStorage];
- }
- }
- // 调用js方法
- - (void)postMessageJS:(NSDictionary *)jsDict {
- NSString *jsString = [jsDict mj_JSONString];
- [self.myWebView evaluateJavaScript:[NSString stringWithFormat:@"sendMessage(%@)", jsString] completionHandler:nil];
- }
- // 6 页面加载失败时调用
- - (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation withError:(NSError *)error {
- NSLog(@"6-------页面加载失败时调用");
- [self showErrorView];
- }
- // 接收到服务器跳转请求之后调用
- - (void)webView:(WKWebView *)webView didReceiveServerRedirectForProvisionalNavigation:(WKNavigation *)navigation {
- NSLog(@"-------接收到服务器跳转请求之后调用");
- }
- // 数据加载发生错误时调用
- - (void)webView:(WKWebView *)webView didFailNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error {
- NSLog(@"----数据加载发生错误时调用");
- // 错误上报
- if (error) {
- if (error.code == -999) {
- NSLog(@"-- error desc - %@", error.description);
- NSMutableDictionary *parm = [NSMutableDictionary dictionary];
- [parm setValue:UserDefault(UIDKey) forKey:@"userId"];
- [parm setValue:@"KSBaseWKWebViewController" forKey:@"Location"];
- [parm setValue:webView.URL.absoluteString forKey:@"url"];
- [parm setValue:@(error.code) forKey:@"errorCode"];
- [parm setValue:error.description forKey:@"errorDesc"];
- [parm setValue:[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"] forKey:@"version"];
-
- NSString *content = [parm mj_JSONString];
- NSMutableDictionary *uploadParm = [KSLogManager generateLogMessageWithContent:content type:@"ERROR"];
- NSMutableArray *uploadArray = [NSMutableArray arrayWithObject:uploadParm];
- [KSNetworkingManager sysExceptionLogUpdate:KS_POST token:UserDefault(TokenKey) logArray:uploadArray success:^(NSDictionary * _Nonnull dic) {
- if ([dic ks_integerValueForKey:@"code"] == 200) {
-
- }
- } faliure:^(NSError * _Nonnull error) {
-
- }];
- }
- }
- }
- - (void)webView:(WKWebView *)webView didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential *_Nullable))completionHandler
- {
- dispatch_queue_t queue = dispatch_queue_create("webViewChallengeQueue", NULL);
- dispatch_async(queue, ^{
- if (SSL_AUTH) {
- NSURLSessionAuthChallengeDisposition disposition = NSURLSessionAuthChallengePerformDefaultHandling;
- NSURLCredential *customCredential = nil;
-
- if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {
- // 默认信任
- customCredential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];
- disposition = NSURLSessionAuthChallengeUseCredential;
- }
- else if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodClientCertificate]) {
- // client authentication
- SecIdentityRef identity = NULL;
- SecTrustRef trust = NULL;
- if ([AuthChallengeManager extractIdentity:&identity andTrust:&trust filePath:CERT_PATH]) {
- SecCertificateRef certificate = NULL;
- SecIdentityCopyCertificate(identity, &certificate);
- const void*certs[] = {certificate};
- CFArrayRef certArray =CFArrayCreate(kCFAllocatorDefault, certs,1,NULL);
- customCredential =[NSURLCredential credentialWithIdentity:identity certificates:(__bridge NSArray*)certArray persistence:NSURLCredentialPersistencePermanent];
- disposition = NSURLSessionAuthChallengeUseCredential;
- }
- }
-
- if (completionHandler) {
- completionHandler(disposition, customCredential);
- }
- }
- else {
- if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {
- if (challenge.previousFailureCount == 0) {
- NSURLCredential *credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];
- completionHandler(NSURLSessionAuthChallengeUseCredential, credential);
- } else {
- completionHandler(NSURLSessionAuthChallengeCancelAuthenticationChallenge, nil);
- }
- }
- else {
- completionHandler(NSURLSessionAuthChallengeCancelAuthenticationChallenge, nil);
- }
- }
- });
- }
- //当因为某些问题,导致webView进程终止时触发
- - (void)webViewWebContentProcessDidTerminate:(WKWebView *)webView {
- NSLog(@"%s", __func__);
- if (self.navigationController.visibleViewController == self) {
- [webView reload];
- }
- else {
- self.needReload = YES;
- }
- }
- /**
- * web界面中有弹出警告框时调用
- *
- * @param webView 实现该代理的webview
- * @param message 警告框中的内容
- * @param completionHandler 警告框消失调用
- */
- - (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler {
- NSLog(@"-------web界面中有弹出警告框时调用");
- NSLog(@"%@",message);
- UIAlertController *alertController = [UIAlertController alertControllerWithTitle:message
- message:nil
- preferredStyle:UIAlertControllerStyleAlert];
- [alertController addAction:[UIAlertAction actionWithTitle:@"确定"
- style:UIAlertActionStyleCancel
- handler:^(UIAlertAction *action) {
- completionHandler();
- }]];
-
- [self presentViewController:alertController animated:YES completion:nil];
- }
- // 取消和确认的按钮
- - (void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL))completionHandler {
- // js 里面的alert实现,如果不实现,网页的alert函数无效 ,
- UIAlertController *alertController = [UIAlertController alertControllerWithTitle:message
- message:nil
- preferredStyle:UIAlertControllerStyleAlert];
- [alertController addAction:[UIAlertAction actionWithTitle:@"确定"
- style:UIAlertActionStyleDefault
- handler:^(UIAlertAction *action) {
- completionHandler(YES);
- }]];
- [alertController addAction:[UIAlertAction actionWithTitle:@"取消"
- style:UIAlertActionStyleCancel
- handler:^(UIAlertAction *action){
- completionHandler(NO);
- }]];
-
- [self presentViewController:alertController animated:YES completion:^{}];
-
- }
- #pragma mark - KVO回馈
- -(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context{
- if ([keyPath isEqualToString:@"estimatedProgress"]) {
- self.progressLayer.opacity = 1;
- if ([change[@"new"] floatValue] <[change[@"old"] floatValue]) {
- return;
- }
- self.progressLayer.frame = CGRectMake(0, 0, kScreenWidth*[change[@"new"] floatValue], 3);
- if ([change[@"new"]floatValue] == 1.0) {
- dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
- self.progressLayer.opacity = 0;
- self.progressLayer.frame = CGRectMake(0, 0, 0, 3);
- });
- }
- }
- }
- /*
- #pragma mark - Navigation
- // In a storyboard-based application, you will often want to do a little preparation before navigation
- - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
- // Get the new view controller using [segue destinationViewController].
- // Pass the selected object to the new view controller.
- }
- */
- - (void)configLocalStorage {
- _hasModify = YES;
- if (![NSString isEmptyString:UserDefault(TokenKey)]) {
- NSString *jsString = [NSString stringWithFormat:@"localStorage.setItem('Authorization', '%@ %@')",UserDefault(Token_type), UserDefault(TokenKey)];
- [self.myWebView evaluateJavaScript:jsString completionHandler:nil];
- }
- }
- - (void)setupProgress {
- UIView *progress = [[UIView alloc]init];
- progress.frame = CGRectMake(0, 0, kScreenWidth, 3);
- progress.backgroundColor = [UIColor clearColor];
- [self.view addSubview:progress];
-
- CALayer *layer = [CALayer layer];
- layer.frame = CGRectMake(0, 0, 0, 3);
- layer.backgroundColor = CLIENT_THEMECOLOR.CGColor;
- [progress.layer addSublayer:layer];
- self.progressLayer = layer;
- }
- + (WKProcessPool*)singleWkProcessPool {
- static WKProcessPool *sharedPool;
- static dispatch_once_t onceToken;
- dispatch_once(&onceToken, ^{
- sharedPool = [[WKProcessPool alloc] init];
- });
- return sharedPool;
- }
- - (NSDictionary *)convertJsonStringToNSDictionary:(NSString *)jsonString {
- if (jsonString == nil) {
- return nil;
- }
- NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
- NSError *error;
- NSDictionary *json = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error];
- if (error) {
- NSLog(@"jsonString解析失败:%@", error);
- return nil;
- }
- return json;
- }
- - (void)dealloc {
- NSLog(@"webView dealloc -----");
- [[_myWebView configuration].userContentController removeScriptMessageHandlerForName:SCRIPT_NAME];
- [_myWebView removeObserver:self forKeyPath:@"estimatedProgress"];
- [_myWebView removeObserver:self forKeyPath:@"title"];
- [_myWebView loadHTMLString:@"" baseURL:nil];
- [_myWebView removeFromSuperview];
- _myWebView = nil;
- [[NSURLCache sharedURLCache] removeAllCachedResponses];
- [[NSURLCache sharedURLCache] setDiskCapacity:0];
- [[NSURLCache sharedURLCache] setMemoryCapacity:0];
- [[NSNotificationCenter defaultCenter] removeObserver:self];
- }
- - (NSString *)getSaveSpeedPath {
- // 在Documents目录下创建一个名为AudioSpeedFile的文件夹
- NSString *path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject] stringByAppendingPathComponent:@"AudioSpeedFile"];
- NSLog(@"%@",path);
-
- NSFileManager *fileManager = [NSFileManager defaultManager];
- BOOL isDir = FALSE;
- BOOL isDirExist = [fileManager fileExistsAtPath:path isDirectory:&isDir];
- if(!(isDirExist && isDir)) {
- BOOL bCreateDir = [fileManager createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil];
- if(!bCreateDir){
- NSLog(@"创建文件夹失败!");
- }
- NSLog(@"创建文件夹成功,文件路径%@",path);
- }
-
- path = [path stringByAppendingPathComponent:@"songSpeed.plist"];
- NSLog(@"file path:%@",path);
- return path;
- }
- #pragma mark -- 上传图片
- - (void)hudTipWillShow:(BOOL)willShow{
- if (willShow) {
- [self resignFirstResponder];
- UIWindow *keyWindow = [UIApplication sharedApplication].keyWindow;
- if (!_HUD) {
- _HUD = [MBProgressHUD showHUDAddedTo:keyWindow animated:YES];
- _HUD.mode = MBProgressHUDModeDeterminateHorizontalBar;
- _HUD.label.text = @"正在上传视频...";
- _HUD.contentColor = [UIColor whiteColor];
- _HUD.bezelView.style = MBProgressHUDBackgroundStyleSolidColor;
- _HUD.bezelView.backgroundColor = HexRGBAlpha(0x000000, 0.8);
- _HUD.removeFromSuperViewOnHide = YES;
-
- }else{
- _HUD.progress = 0;
- [keyWindow addSubview:_HUD];
- [_HUD showAnimated:YES];
- }
- }else{
- [_HUD hideAnimated:YES];
- }
- }
- - (void)uploadImageArray:(NSMutableArray *)imageArray bucket:(NSString *)bucket {
- [LOADING_MANAGER showHUD];
- NSMutableArray *imageDataArray = [NSMutableArray array];
- for (UIImage *image in imageArray) {
- NSData *imgData = [UIImage turnsImaegDataByImage:image];
- [imageDataArray addObject:imgData];
- }
- [UPLOAD_MANAGER configWithfilePath:@"/user/"];
- [UPLOAD_MANAGER mutilUploadImage:imageDataArray fileName:@"complainImg" successCallback:^(NSMutableArray * _Nonnull fileUrlArray) {
- [LOADING_MANAGER removeHUD];
- NSMutableArray *urlArray = [NSMutableArray array];
- for (NSString *url in fileUrlArray) {
- [urlArray addObject:url];
- }
- NSString *attachments = [urlArray componentsJoinedByString:@","];
- if (self.chooseFileParm) { // 回调
- [self.chooseFileParm setValue:attachments forKey:@"fileUrl"];
- [self postMessage:self.chooseFileParm];
- self.chooseFileParm = nil;
- }
- } faliure:^(NSError * _Nullable error, NSString * _Nullable descMessaeg) {
- [LOADING_MANAGER removeHUD];
- [LOADING_MANAGER MBShowAUTOHidingInWindow:descMessaeg];
- [self fileChooseErrorCallback];
- }];
- }
- #pragma mark --- 上传视频文件
- - (void)uploadVideoWithUrl:(NSString *)videoUrl bucket:(NSString *)bucket {
- // 取出视频第一帧
- UIImage *previewImage = [self firstFrameWithVideoURL:[NSURL fileURLWithPath:videoUrl] size:CGSizeMake(1280, 720)];
- __block NSString *imageUrl = @"";
- if (previewImage) { // 如果有第一帧
- NSData *imgData = [UIImage turnsImaegDataByImage:previewImage];
- NSString *fileName = @"videoPreviewImg";
- [UPLOAD_MANAGER configWithfilePath:@"/user/"];
- [UPLOAD_MANAGER uploadImage:imgData fileName:fileName successCallback:^(NSMutableArray * _Nonnull fileUrlArray) {
- NSString *url = [fileUrlArray lastObject];
- imageUrl = url;
- [self submitUrlWith:imageUrl videoUrl:videoUrl];
- } faliure:^(NSError * _Nullable error, NSString *descMessaeg) {
- if (![NSString isEmptyString:descMessaeg]) {
- [LOADING_MANAGER MBShowAUTOHidingInWindow:descMessaeg];
- }
- [self fileChooseErrorCallback];
- }];
- }
- else {
- [self submitUrlWith:nil videoUrl:videoUrl];
- }
- }
- - (void)submitUrlWith:(NSString *)imgUrl videoUrl:(NSString *)videoUrl {
- // 上传视频
- [self hudTipWillShow:YES];
- NSURL *uploadFileUrl = [NSURL fileURLWithPath:videoUrl];
- NSData *fileData = [NSData dataWithContentsOfURL:uploadFileUrl];
- NSString *suffix = [NSString stringWithFormat:@".%@",[uploadFileUrl pathExtension]];
- [UPLOAD_MANAGER videoUpload:fileData fileName:@"video" fileSuffix:suffix progress:^(int64_t bytesWritten, int64_t totalBytes) {
- dispatch_main_async_safe(^{
- // 显示进度
- if (self.HUD) {
- self.HUD.progress = bytesWritten / totalBytes;// progress是回调进度
- }
- });
- } successCallback:^(NSMutableArray * _Nonnull fileUrlArray) {
- [self hudTipWillShow:NO];
- NSString *fileUrl = [fileUrlArray lastObject];
- [self videoUploadCallback:fileUrl firstFrameImg:imgUrl];
- } faliure:^(NSError * _Nullable error, NSString * _Nullable descMessaeg) {
- [self hudTipWillShow:NO];
- if (![NSString isEmptyString:descMessaeg]) {
- [LOADING_MANAGER MBShowAUTOHidingInWindow:descMessaeg];
- }
- [self videoUploadCallback:@"" firstFrameImg:@""];
- }];
- }
- - (void)videoUploadCallback:(NSString *)remoteVideoUrl firstFrameImg:(NSString *)imgUrl {
- if (self.chooseFileParm) { // 回调
- [self.chooseFileParm setValue:remoteVideoUrl forKey:@"fileUrl"];
- [self.chooseFileParm setValue:imgUrl forKey:@"firstFrameImg"];
- [self postMessage:self.chooseFileParm];
- self.chooseFileParm = nil;
- }
- }
- #pragma mark ---- 获取图片第一帧
- - (UIImage *)firstFrameWithVideoURL:(NSURL *)url size:(CGSize)size
- {
- // 获取视频第一帧
- NSDictionary *opts = [NSDictionary dictionaryWithObject:[NSNumber numberWithBool:NO] forKey:AVURLAssetPreferPreciseDurationAndTimingKey];
- AVURLAsset *urlAsset = [AVURLAsset URLAssetWithURL:url options:opts];
- AVAssetImageGenerator *generator = [AVAssetImageGenerator assetImageGeneratorWithAsset:urlAsset];
- generator.appliesPreferredTrackTransform = YES;
- generator.maximumSize = CGSizeMake(size.width, size.height);
- NSError *error = nil;
- CGImageRef imgRef = [generator copyCGImageAtTime:CMTimeMake(0, 10) actualTime:NULL error:&error];
- if (imgRef) {
- UIImage *image = [UIImage imageWithCGImage:imgRef];
- CGImageRelease(imgRef);
- return image;
- }
- else {
- return nil;
- }
- }
- #pragma mark ---- UIDocumentPickerDelegate
- - (void)documentPickerWasCancelled:(UIDocumentPickerViewController *)controller {
- if (self.isDownloadFile) {
- self.isDownloadFile = NO;
- }
- else {
- [self fileChooseErrorCallback];
- }
- }
- - (void)fileChooseErrorCallback {
- if (self.chooseFileParm) { // 回调
- [self.chooseFileParm setValue:@"" forKey:@"fileUrl"];
- [self postMessage:self.chooseFileParm];
- self.chooseFileParm = nil;
- }
- }
- - (void)uploadFile:(NSString *)fileName fileUrl:(NSString *)fileUrl {
- dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
- [LOADING_MANAGER showHUD];
- NSString *suffix = [NSString stringWithFormat:@".%@",[[fileName componentsSeparatedByString:@"."] lastObject]];
- NSData *fileData = [NSData dataWithContentsOfURL:[NSURL fileURLWithPath:fileUrl]];
- [UPLOAD_MANAGER configWithfilePath:@"/user/"];
- [UPLOAD_MANAGER uploadFile:fileData fileName:@"file" fileSuffix:suffix progress:^(int64_t bytesWritten, int64_t totalBytes) {
- int progress = (int)(bytesWritten / totalBytes * 100);
- __block NSString *tipsMessage = [NSString stringWithFormat:@"上传中 %d%%",progress];
- dispatch_main_async_safe(^{
- [LOADING_MANAGER.loadingView setDisplayText:tipsMessage];
- });
- } successCallback:^(NSMutableArray * _Nonnull fileUrlArray) {
- [LOADING_MANAGER removeHUD];
- NSString *fileUrl = [fileUrlArray lastObject];
- if (self.chooseFileParm) { // 回调
- [self.chooseFileParm setValue:fileUrl forKey:@"fileUrl"];
- [self postMessage:self.chooseFileParm];
- self.chooseFileParm = nil;
- }
- } faliure:^(NSError * _Nullable error, NSString * _Nullable descMessaeg) {
- [LOADING_MANAGER removeHUD];
- [LOADING_MANAGER MBShowAUTOHidingInWindow:descMessaeg];
- [self fileChooseErrorCallback];
- }];
- });
- }
- - (CGFloat)getFileSize:(NSURL *)fileUrl {
- NSFileManager *fileManager = [NSFileManager defaultManager];
- float filesize = -1.0;
- NSString *path = fileUrl.path;
- if ([fileManager fileExistsAtPath:path]) {
- NSDictionary *fileDic = [fileManager attributesOfItemAtPath:path error:nil];//获取文件的属性
- unsigned long long size = [[fileDic objectForKey:NSFileSize] longLongValue];
- filesize = 1.0*size/1024/1024;
- }
- return filesize;
- }
- #pragma mark - UIDocumentInteractionControllerDelegate
- -(UIViewController*)documentInteractionControllerViewControllerForPreview:(UIDocumentInteractionController*)controller{
- return self;
- }
- -(UIView*)documentInteractionControllerViewForPreview:(UIDocumentInteractionController*)controller {
- return self.view;
- }
- -(CGRect)documentInteractionControllerRectForPreview:(UIDocumentInteractionController*)controller {
- return self.view.frame;
- }
- #pragma mark - UIDocumentPickerDelegate
- - (void)documentPicker:(UIDocumentPickerViewController *)controller didPickDocumentsAtURLs:(NSArray <NSURL *>*)urls {
- if (self.isDownloadFile) {
- self.isDownloadFile = NO;
- //保存成功
- [LOADING_MANAGER MBShowAUTOHidingInWindow:@"保存成功"];
- }
- else {
- NSURL *url = [urls lastObject];
- NSArray *array = [[url absoluteString] componentsSeparatedByString:@"/"];
- NSString *fileName = [array lastObject];
- fileName = [fileName stringByRemovingPercentEncoding];
-
- if (self.fileChooseType == CHOOSETYPE_XML) {
- if (![fileName hasSuffix:@".xml"]) {
- [LOADING_MANAGER MBShowAUTOHidingInWindow:@"请上传XML格式文件"];
- [self fileChooseErrorCallback];
- return;
- }
- }
- else if (self.fileChooseType == CHOOSETYPE_MIDI) {
- if (![fileName hasSuffix:@".mid"] || [fileName hasSuffix:@".midi"]) {
- [LOADING_MANAGER MBShowAUTOHidingInWindow:@"请上传mid格式文件"];
- [self fileChooseErrorCallback];
- return;
- }
- }
- else if (self.fileChooseType == CHOOSETYPE_MP3) {
- if (![fileName hasSuffix:@".mp3"]) {
- [LOADING_MANAGER MBShowAUTOHidingInWindow:@"请上传mp3格式文件"];
- [self fileChooseErrorCallback];
- return;
- }
- }
- else {
- if (![fileName hasSuffix:@".mp3"] && ![fileName hasSuffix:@".aac"]) {
- [LOADING_MANAGER MBShowAUTOHidingInWindow:@"暂不支持此格式!"];
- [self fileChooseErrorCallback];
- return;
- }
- }
-
- __block NSString * fileUrl = @"";
- if ([KSICloudManager iCloudEnable]) {
- [KSICloudManager downloadWithDocumentURL:url callBack:^(id obj) {
- NSData *data = obj;
-
- //写入沙盒Documents
- NSString *pathStr = [NSHomeDirectory() stringByAppendingString:[NSString stringWithFormat:@"/Documents/%@",fileName]];
- [data writeToFile:pathStr atomically:YES];
-
- if (![[NSFileManager defaultManager] fileExistsAtPath:pathStr]) {
- BOOL isSuccess = [data writeToFile:pathStr atomically:YES];
- if (isSuccess) {
- fileUrl = pathStr;
- }
- else {
- [LOADING_MANAGER MBShowAUTOHidingInWindow:@"写入文件错误!"];
- [self fileChooseErrorCallback];
- }
- }
- else {
- fileUrl = pathStr;
- }
- [self uploadFile:fileName fileUrl:pathStr];
-
- }];
- }
- else {
- [LOADING_MANAGER MBShowAUTOHidingInWindow:@"iCloud不可用!"];
- [self fileChooseErrorCallback];
- }
- }
- }
- #pragma mark ---- 镜像和投屏检测
- - (void)captureViewTips:(NSNotification *)notification {
- [self checkCaptured];
- }
- - (void)checkCaptured {
- dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
- if ([self checkIsCaptured]) {
- [self didCapturedView];
- }
- });
- }
- - (BOOL)checkIsCaptured {
- if ([UIScreen mainScreen].isCaptured && [UIScreen screens].count < 2) {
- return YES;
- }
- return NO;
- }
- - (void)didCapturedView {
-
- NSMutableDictionary *sendParm = [NSMutableDictionary dictionary];
- [sendParm setValue:@"setVideoPlayer" forKey:@"api"];
- NSMutableDictionary *content = [NSMutableDictionary dictionary];
- [content setValue:@"pause" forKey:@"status"];
- [sendParm setValue:content forKey:@"content"];
- [self postMessage:sendParm];
- }
- - (KSWebLoadRefreshView *)errorView {
- if (!_errorView) {
- _errorView = [KSWebLoadRefreshView shareInstance];
- MJWeakSelf;
- [_errorView failViewActionCallback:^(BOOL isBack) {
- [weakSelf hideErrorView];
- if (isBack) {
- [weakSelf backAction];
- }
- else {
- [weakSelf loadRequest];
- }
- }];
- }
- return _errorView;
- }
- - (void)showErrorView {
- if (![self.view.subviews containsObject:self.errorView]) {
- [self.view addSubview:self.errorView];
- [self.errorView mas_makeConstraints:^(MASConstraintMaker *make) {
- make.left.right.top.bottom.mas_equalTo(self.view);
- }];
- [self.view bringSubviewToFront:self.errorView];
- }
- }
- - (void)hideErrorView {
- if ([self.view.subviews containsObject:self.errorView]) {
- [self.errorView removeFromSuperview];
- }
- }
- /*
- #pragma mark - Navigation
- // In a storyboard-based application, you will often want to do a little preparation before navigation
- - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
- // Get the new view controller using [segue destinationViewController].
- // Pass the selected object to the new view controller.
- }
- */
- @end
|