12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346 |
- //
- // KSBaseWKWebViewController.m
- // KulexiuForTeacher
- //
- // Created by Kyle on 2022/3/17.
- //
- #import "KSBaseWKWebViewController.h"
- #import "JPUSHService.h"
- #import "LoginViewController.h"
- #import "AppDelegate.h"
- #import "CustomNavViewController.h"
- #import <RongIMKit/RongIMKit.h>
- #import "UIDevice+TFDevice.h"
- #import "KSPremissionAlert.h"
- #import "RecordCheckManager.h"
- #import "KSLocalWebViewController.h"
- #import "RCConnectionManager.h"
- #import "KSAccompanyWebViewController.h"
- #import "KSChatConversationViewController.h"
- #import "KSGroupConversationController.h"
- #import "KSOrderManager.h"
- #import "AddressListViewController.h"
- #import "KSEnterLiveroomManager.h"
- #import "TZImageManager.h"
- #import <AVFoundation/AVFoundation.h>
- #import "KSDocumentViewController.h"
- #import "KSICloudManager.h"
- #import "KSMediaManager.h"
- #import "KSUMShareManager.h"
- #import "UserInfoManager.h"
- typedef NS_ENUM(NSInteger, CHOOSETYPE) {
- CHOOSETYPE_XML,
- CHOOSETYPE_MIDI,
- CHOOSETYPE_MP3,
- CHOOSETYPE_ALL,
- };
- @interface KSBaseWKWebViewController ()<UIDocumentPickerDelegate>
- @property (nonatomic, assign) BOOL isOutLink; // 外部链接
- @property (nonatomic,weak) CALayer *progressLayer;
- @property (nonatomic, strong) NSString *currerntURL; // 当前web URL
- @property (nonatomic, assign) BOOL hasModify;
- @property (nonatomic, assign) BOOL hasChangeSource; // 是否切换了亮屏,横屏等配置
- @property (nonatomic, assign) BOOL landScape;
- /// 选择本地文件 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;
- @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)captureViewTips:(NSNotification *)notification {
- if ([UIScreen mainScreen].isCaptured) {
- [self didCapturedView];
- }
- }
- - (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];
-
- // [self MBPShow:@"为了保证数据安全,请不要录屏"];
- }
- - (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;
- if (_landScape != isLandScape) {
- [self changeOrientation:isLandScape];
- }
- // 是否隐藏头部导航条
- self.hideTop = [parmDic ks_boolValueForKey:@"isHideTitle"];
- }
- - (void)changeOrientation:(BOOL)isLandScape {
- self.landScape = isLandScape;
- if (isLandScape) {
- // 切换到横屏
- AppDelegate* delegate = (AppDelegate*)[UIApplication sharedApplication].delegate;
- delegate.allowAutoRotate = YES;
- [UIDevice switchNewOrientation:UIInterfaceOrientationLandscapeRight inController:self];
- }
- else {
- AppDelegate* delegate = (AppDelegate*)[UIApplication sharedApplication].delegate;
- delegate.allowAutoRotate = NO;
- [UIDevice switchNewOrientation:UIInterfaceOrientationPortrait inController:self];
- }
- }
- - (void)viewWillAppear:(BOOL)animated {
- [super viewWillAppear:animated];
- if (_hasChangeSource) {
- [self setParmDic:self.parmDic];
- }
- if (self.isFirstLoad == NO) {
- [self sendResumeMessage];
- }
- self.isFirstLoad = NO;
-
- if ([UIScreen mainScreen].isCaptured) {
- [self didCapturedView];
- }
- }
- - (void)sendResumeMessage {
-
- NSMutableDictionary *parm = [NSMutableDictionary dictionary];
- [parm setValue:@"webViewOnResume" forKey:@"api"];
- [self postMessage:parm];
- }
- - (void)viewWillDisappear:(BOOL)animated {
- [super viewWillDisappear:animated];
- if (_hasChangeSource && self.keepOrientation == NO && self.landScape == YES) {
- [[UIApplication sharedApplication] setIdleTimerDisabled:NO];
- [self changeOrientation:NO];
- }
- self.keepOrientation = NO;
- }
- - (void)initWebView {
-
- [self.view addSubview:self.navView];
- CGFloat topHeight = kNaviBarHeight;
- if (self.hideTop) {
- topHeight = 0.0f;
- }
- [self.navView mas_makeConstraints:^(MASConstraintMaker *make) {
- make.left.right.top.mas_equalTo(self.view);
- make.height.mas_equalTo(topHeight);
- }];
-
- [self.view addSubview:self.webBackButton];
- [self.webBackButton mas_makeConstraints:^(MASConstraintMaker *make) {
- make.left.top.mas_equalTo(self.view);
- make.height.mas_equalTo(kNaviBarHeight);
- make.width.mas_equalTo(44);
- }];
- if (self.hideTop) {
- self.webBackButton.hidden = YES;
- }
- if (_hiddenNavBar) {
- topHeight = 0.0f;
- }
- if (self.headTitle) {
- [self.navView.topTitleLabel setText:_headTitle];
- }
-
- if (_myWebView == nil) {
-
- WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
- config.selectionGranularity = WKSelectionGranularityDynamic;
- config.allowsInlineMediaPlayback = YES;
- if (@available(iOS 10.0, *)) {
- config.mediaTypesRequiringUserActionForPlayback = NO;
- } else {
- // Fallback on earlier versions
- config.requiresUserActionForMediaPlayback = 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:@"COLEXIU"];
- 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;
- // 加载进度条和title
- [_myWebView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
- [_myWebView addObserver:self forKeyPath:@"title" options:NSKeyValueObservingOptionNew context:NULL];
- if (@available(iOS 16.4, *)) {
- _myWebView.inspectable = YES;
- }
- [self.view addSubview:_myWebView];
- [_myWebView mas_makeConstraints:^(MASConstraintMaker *make) {
- make.left.right.mas_equalTo(self.view);
- make.top.mas_equalTo(self.view.mas_top).offset(topHeight);
- make.bottom.mas_equalTo(self.view.mas_bottom);
- }];
- if (@available(iOS 11.0, *)) {
- _myWebView.scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
- } else {
- // Fallback on earlier versions
- }
- [self setupProgress];
- // 修改userAgent
- [self loadRequest];
- [self.view bringSubviewToFront:self.navView];
- [self.view bringSubviewToFront:self.webBackButton];
- }
- else {
- [_myWebView reload];
- }
- }
- - (void)configUserAgent:(WKWebViewConfiguration *)config {
- NSString *oldUserAgent = config.applicationNameForUserAgent;
- NSString *newAgent = [NSString stringWithFormat:@"%@ %@ %@",oldUserAgent,@"COLEXIUAPPI",@"COLEXIUSTUDENT"];
- 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)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:@"COLEXIU"]) {
- 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.navigationController popViewControllerAnimated:YES];
- }
- 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;
- if (isLandScape == self.landScape) {
- self.keepOrientation = YES;
- detailCtrl.keepOrientation = YES;
- }
- [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 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) {
- MJWeakSelf;
- [self KSShowMsg:@"下载成功" promptCompletion:^{
- [weakSelf 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"]) { // 打开伴奏
- PREMISSIONTYPE micEnable = [RecordCheckManager checkPermissionShowAlert:NO showInView:nil];
- PREMISSIONTYPE cameraEnable = [RecordCheckManager checkCameraPremissionAvaiable:NO showInView:nil];
- if (micEnable == PREMISSIONTYPE_YES && cameraEnable == PREMISSIONTYPE_YES) { // 如果麦克风和摄像头权限都有
- NSDictionary *valueDic = [parm ks_dictionaryValueForKey:@"content"];
- KSAccompanyWebViewController *detailCtrl = [[KSAccompanyWebViewController alloc] init];
- detailCtrl.url = [valueDic ks_stringValueForKey:@"url"];
- detailCtrl.parmDic = valueDic;
- detailCtrl.hiddenNavBar = [valueDic ks_boolValueForKey:@"isHideTitle"];
- NSInteger orientation = [valueDic ks_integerValueForKey:@"orientation"];
- BOOL isLandScape = orientation == 0 ? YES : NO;
- if (isLandScape == self.landScape) {
- self.keepOrientation = YES;
- detailCtrl.keepOrientation = YES;
- }
- [self postMessage:parm];
- [self.navigationController pushViewController:detailCtrl animated:YES];
- }
- else {
- if (micEnable == PREMISSIONTYPE_NO && cameraEnable == PREMISSIONTYPE_NO) { // 如果麦克风权限和摄像头权限都没有
- [self showAlertWithMessage:@"请开启相机和麦克风访问权限" type:CHECKDEVICETYPE_BOTH];
- }
- else if (micEnable == PREMISSIONTYPE_NO) { // 如果没有麦克风权限
- [self showAlertWithMessage:@"请开启麦克风访问权限" type:CHECKDEVICETYPE_MIC];
- }
- else if (cameraEnable == PREMISSIONTYPE_NO) { // 如果没有摄像头权限
- [self showAlertWithMessage:@"请开启相机访问权限" type:CHECKDEVICETYPE_CAMREA];
- }
- }
- }
- else if ([[parm ks_stringValueForKey:@"api"] isEqualToString:@"checkAlbum"]) { // 判断权限
- [self postMessage:parm];
- PREMISSIONTYPE albumEnable = [RecordCheckManager checkPhotoLibraryPremissionAvaiable:NO showInView:nil];
- if (albumEnable == PREMISSIONTYPE_NO) {
- [self showAlertWithMessage:@"请开启相册访问权限" type:CHECKDEVICETYPE_CAMREA];
- }
- }
- else if ([[parm ks_stringValueForKey:@"api"] isEqualToString:@"shareAchievements"]) { // 分享
- //
- [self shareFunctionWithParm:parm];
- }
- 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:@"backIconChange"]) {
- NSDictionary *valueDic = [parm ks_dictionaryValueForKey:@"content"];
- NSString *backColor = [valueDic ks_stringValueForKey:@"iconStyle"];
- NSString *backImage = @"";
- if ([backColor isEqualToString:@"black"]) {
- backImage = @"back_black";
- }
- else {
- backImage = @"back_button_white";
- }
- [self.webBackButton.backButton setImage:[UIImage imageNamed:backImage] forState:UIControlStateNormal];
- }
- else if ([[parm ks_stringValueForKey:@"api"] isEqualToString:@"setBarStatus"]) { // 顶部是否隐藏
- NSDictionary *valueDic = [parm ks_dictionaryValueForKey:@"content"];
- BOOL isShow = [valueDic ks_boolValueForKey:@"status"]; // 0 隐藏 1 显示
- self.hiddenNavBar = !isShow;
- CGFloat navHeight = isShow ? kNaviBarHeight : 0;
- [self.navView mas_updateConstraints:^(MASConstraintMaker *make) {
- make.height.mas_equalTo(navHeight);
- }];
-
- [self.myWebView mas_updateConstraints:^(MASConstraintMaker *make) {
- make.top.mas_equalTo(self.view.mas_top).offset(navHeight);
- }];
- }
- 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:@"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]) {
- [self MBPShow:@"报名未结束,暂无群组"];
- 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:@"joinLiveRoom"]) { // 进入直播间
- NSDictionary *valueDic = [parm ks_dictionaryValueForKey:@"content"];
- NSString *roomId = [valueDic ks_stringValueForKey:@"roomId"];
- [self showhud];
- [KSEnterLiveroomManager joinLiveWithRoomId:roomId inController:(CustomNavViewController *)self.navigationController callback:^{
- [self removehub];
- }];
- }
- else if ([[parm ks_stringValueForKey:@"api"] isEqualToString:@"savePicture"]) { // 保存图片到相册
- // 判断相册权限
- PREMISSIONTYPE albumEnable = [RecordCheckManager checkPhotoLibraryPremissionAvaiable:NO showInView:nil];
- if (albumEnable == 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 {
- if (albumEnable == PREMISSIONTYPE_NO) {
- [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"]) {
- NSString *status = [UIScreen mainScreen].isCaptured ? @"1" : @"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];
- if ([status isEqualToString:@"1"]) {
- [self MBPShow:@"为了保证数据安全,请不要录屏"];
- }
- }
- }
- else if ([[parm ks_stringValueForKey:@"api"] isEqualToString:@"setEventTracking"]) {
- NSString *type = [[parm ks_dictionaryValueForKey:@"content"] ks_stringValueForKey:@"type"];
- [USER_MANAGER sendUMEvent:type];
- }
- }
- - (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"]) {
- [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) {
- [self 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;
- }
- }
-
- [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"];
- [self postMessage:responParm];
- }];
- }
- - (void)showAlertWithMessage:(NSString *)message type:(CHECKDEVICETYPE)deviceType {
- [KSPremissionAlert shareInstanceDisplayImage:deviceType message:message showInView:self.view cancel:^{
-
- } confirm:^{
- [self openSettingView];
- }];
-
- }
- - (void)openSettingView {
- if (@available(iOS 10, *)) {
- [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString] options:@{} completionHandler:nil];
- } else {
- [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
- }
- }
- - (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 logoutAction];
- }
-
- #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 {
- NSLog(@"6-------页面加载失败时调用");
- }
- // 接收到服务器跳转请求之后调用
- - (void)webView:(WKWebView *)webView didReceiveServerRedirectForProvisionalNavigation:(WKNavigation *)navigation {
- NSLog(@"-------接收到服务器跳转请求之后调用");
- }
- // 数据加载发生错误时调用
- - (void)webView:(WKWebView *)webView didFailNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error {
- NSLog(@"----数据加载发生错误时调用");
- }
- - (void)webView:(WKWebView *)webView didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential *_Nullable))completionHandler
- {
- if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {
- if (challenge.previousFailureCount == 0) {
- NSURLCredential *credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];
- completionHandler(NSURLSessionAuthChallengeUseCredential, credential);
- } else {
- completionHandler(NSURLSessionAuthChallengeCancelAuthenticationChallenge, nil);
- }
- }
- }
- //当因为某些问题,导致webView进程终止时触发
- - (void)webViewWebContentProcessDidTerminate:(WKWebView *)webView {
- NSLog(@"%s", __func__);
- [webView reload];
- }
- /**
- * 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);
- });
- }
- }else if ([keyPath isEqualToString:@"title"]) {
- // 顶部title
- self.headTitle = change[@"new"];
- if (self.hiddenNavBar == NO) {
- self.navView.topTitleLabel.text = self.headTitle;
- }
- }
- }
- /*
- #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 = 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)setHiddenNavBar:(BOOL)hiddenNavBar {
- _hiddenNavBar = hiddenNavBar;
- if (hiddenNavBar) {
- self.navView.topTitleLabel.text = @"";
- }
- else {
- self.navView.topTitleLabel.text = self.headTitle;
- }
- }
- #pragma mark --- lazying
- - (KSWebNavView *)navView {
- if (!_navView) {
- _navView = [[KSWebNavView alloc] init];
-
- }
- return _navView;
- }
- - (KSWebBackButton *)webBackButton {
- if (!_webBackButton) {
- _webBackButton = [[KSWebBackButton alloc] init];
- MJWeakSelf;
- [_webBackButton webViewBackAction:^{
- [weakSelf backAction];
- }];
- }
- return _webBackButton;
- }
- - (void)dealloc {
- NSLog(@"webView dealloc -----");
- [[_myWebView configuration].userContentController removeScriptMessageHandlerForName:@"COLEXIU"];
- [_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 = [UIColor colorWithHexString:@"#000000" alpha: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 {
- [self showhud];
- NSMutableArray *imageDataArray = [NSMutableArray array];
- for (UIImage *image in imageArray) {
- NSData *imgData = [UIImage turnsImaegDataByImage:image];
- [imageDataArray addObject:imgData];
- }
- [[KSUploadManager shareInstance] configBucketName:bucket];
- [[KSUploadManager shareInstance] mutilUploadImage:imageDataArray fileName:@"complainImg" successCallback:^(NSMutableArray * _Nonnull fileUrlArray) {
- [self removehub];
- 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) {
- [self removehub];
- [self MBPShow: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";
- [[KSUploadManager shareInstance] configBucketName:bucket];
- [[KSUploadManager shareInstance] 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]) {
- [self MBPShow: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]];
- [[KSUploadManager shareInstance] 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]) {
- [self MBPShow: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 {
- [self fileChooseErrorCallback];
- }
- - (void)fileChooseErrorCallback {
- if (self.chooseFileParm) { // 回调
- [self.chooseFileParm setValue:@"" forKey:@"fileUrl"];
- [self postMessage:self.chooseFileParm];
- self.chooseFileParm = nil;
- }
- }
- - (void)documentPicker:(UIDocumentPickerViewController *)controller didPickDocumentAtURL:(NSURL *)url {
- NSArray *array = [[url absoluteString] componentsSeparatedByString:@"/"];
- NSString *fileName = [array lastObject];
- fileName = [fileName stringByRemovingPercentEncoding];
-
- if (self.fileChooseType == CHOOSETYPE_XML) {
- if (![fileName hasSuffix:@".xml"]) {
- [self MBPShow:@"请上传XML格式文件"];
- [self fileChooseErrorCallback];
- return;
- }
- }
- else if (self.fileChooseType == CHOOSETYPE_MIDI) {
- if (![fileName hasSuffix:@".mid"] || [fileName hasSuffix:@".midi"]) {
- [self MBPShow:@"请上传mid格式文件"];
- [self fileChooseErrorCallback];
- return;
- }
- }
- else if (self.fileChooseType == CHOOSETYPE_MP3) {
- if (![fileName hasSuffix:@".mp3"]) {
- [self MBPShow:@"请上传mp3格式文件"];
- [self fileChooseErrorCallback];
- return;
- }
- }
- else {
- if (![fileName hasSuffix:@".mp3"] && ![fileName hasSuffix:@".aac"]) {
- [self MBPShow:@"暂不支持此格式!"];
- [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 {
- [self MBPShow:@"写入文件错误!"];
- [self fileChooseErrorCallback];
- }
- }
- else {
- fileUrl = pathStr;
- }
- [self uploadFile:fileName fileUrl:pathStr];
-
- }];
- }
- else {
- [self MBPShow:@"iCloud不可用!"];
- [self fileChooseErrorCallback];
- }
- }
- - (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(), ^{
- [self showhud];
- NSString *suffix = [NSString stringWithFormat:@".%@",[[fileName componentsSeparatedByString:@"."] lastObject]];
- NSData *fileData = [NSData dataWithContentsOfURL:[NSURL fileURLWithPath:fileUrl]];
- [[KSUploadManager shareInstance] configBucketName:self.bucketName];
- [[KSUploadManager shareInstance] uploadFile:fileData fileName:@"file" fileSuffix:suffix successCallback:^(NSMutableArray * _Nonnull fileUrlArray) {
- [self removehub];
- 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) {
- [self removehub];
- [self MBPShow: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 - 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
|