dkahgld

ZBAdWebViewController.m 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463
  1. //
  2. // ZBAdWebViewController.m
  3. // ZBProject
  4. //
  5. // Created by 学丽 on 2019/4/10.
  6. // Copyright © 2019 ZB. All rights reserved.
  7. //
  8. #import "ZBAdWebViewController.h"
  9. static NSString *refresh_h5 = @"refresh_h5";
  10. static NSString *app_h5_get_token = @"app_h5_get_token";//获取token
  11. static NSString *app_h5_save_message=@"app_h5_save_message";
  12. static NSString *app_h5_get_message=@"app_h5_get_message";
  13. static NSString *app_h5_to_goodsdetail=@"app_h5_to_goodsdetail";
  14. @interface ZBAdWebViewController ()<WKUIDelegate, WKNavigationDelegate,WKScriptMessageHandler>
  15. @property (nonatomic, strong) WKWebView *webView;
  16. /** 加载进度条 */
  17. @property (nonatomic, strong) UIProgressView *progressView;
  18. @property (nonatomic, strong) UIButton *backButton;
  19. @property (nonatomic, strong) UIButton *closeButton;
  20. @property (nonatomic, strong) UIButton *refreshButton;
  21. @end
  22. @implementation ZBAdWebViewController
  23. - (void)viewDidLoad {
  24. [super viewDidLoad];
  25. [self addNotification];
  26. [self configNavigationBar];
  27. [self addUserhandler];
  28. [self loadRequest];
  29. }
  30. -(void)viewDidAppear:(BOOL)animated
  31. {
  32. [super viewDidAppear:animated];
  33. [_backButton setImage:[UIImage imageNamed:@"back"] forState:UIControlStateNormal];
  34. self.navBar.backgroundColor = [UIColor clearColor];
  35. [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault];
  36. }
  37. - (void)addNotification {
  38. [[NSNotificationCenter defaultCenter] addObserver:self
  39. selector:@selector(refreshH5Action)
  40. name:UIApplicationDidBecomeActiveNotification object:nil];
  41. [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(endFullScreen) name:UIWindowDidBecomeHiddenNotification object:nil];
  42. }
  43. //处理web视频全屏播放时 状态栏消失
  44. - (void)endFullScreen {
  45. [[UIApplication sharedApplication]setStatusBarHidden:false animated:false];
  46. }
  47. - (void)configNavigationBar {
  48. self.view.backgroundColor = [UIColor whiteColor];
  49. [self.view addSubview:self.webView];
  50. [self.view addSubview:self.progressView];
  51. self.navBar.showNavigationBarBottomLine = YES;
  52. [self.navBar setCustomLeftButtons:@[self.backButton]];
  53. [self.navBar setCustomRightButtons:@[self.refreshButton]];
  54. if (@available(iOS 11.0, *)) {
  55. self.webView.scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;//UIScrollView也适用
  56. }else {
  57. self.automaticallyAdjustsScrollViewInsets = NO;
  58. }
  59. }
  60. - (void)addUserhandler {
  61. [[self.webView configuration].userContentController addScriptMessageHandler:[[WYWeakScriptMessageDelegate alloc] initWithDelegate:self] name:app_h5_get_token];
  62. [[self.webView configuration].userContentController addScriptMessageHandler:[[WYWeakScriptMessageDelegate alloc] initWithDelegate:self] name:app_h5_save_message];
  63. [[self.webView configuration].userContentController addScriptMessageHandler:[[WYWeakScriptMessageDelegate alloc] initWithDelegate:self] name:app_h5_get_message];
  64. [[self.webView configuration].userContentController addScriptMessageHandler:[[WYWeakScriptMessageDelegate alloc] initWithDelegate:self] name:app_h5_to_goodsdetail];
  65. }
  66. #pragma mark --- WKScriptMessageHandler
  67. - (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
  68. if ([message.name isEqualToString:app_h5_get_token]){
  69. //传token给js
  70. [self sendUserTokenToJS:message];
  71. }else if ([message.name isEqualToString:app_h5_save_message])
  72. {
  73. [self saveLocal:message];
  74. }else if ([message.name isEqualToString:app_h5_get_message])
  75. {
  76. [self sendmessageToJS:message];
  77. }else if ([message.name isEqualToString:app_h5_to_goodsdetail])
  78. {//跳转详情
  79. [self getGoodDetail:message];
  80. }
  81. }
  82. #pragma mark--跳转详情
  83. -(void)getGoodDetail:(WKScriptMessage *)message
  84. {
  85. NSDictionary *dict = [self dictionaryWithJsonString:message.body];
  86. ZBGoodModel *model =[[ZBGoodModel alloc]init];
  87. model.goods_id = [NSString stringWithFormat:@"%@",dict[@"goodsId"]];
  88. ZBGoodDetailVC *detailVC = [[ZBGoodDetailVC alloc] init];
  89. detailVC.model = model;
  90. [self.navigationController pushViewController:detailVC animated:YES];
  91. }
  92. #pragma mark---保存本地
  93. -(void)saveLocal:(WKScriptMessage *)message
  94. {
  95. NSLog(@"%@",message.body);
  96. NSDictionary *dic =[self dictionaryWithJsonString:message.body];
  97. [PublicFunction saveMessage:dic];
  98. }
  99. /**
  100. 传消息给js
  101. */
  102. - (void)sendmessageToJS:(WKScriptMessage *)message {
  103. NSDictionary *dict = [self dictionaryWithJsonString:message.body];
  104. NSString *jsMethod = dict[@"js_callback"];
  105. NSDictionary *tokenPara = [PublicFunction getMessage];
  106. if (tokenPara.allKeys.count == 0) {
  107. return;
  108. }
  109. NSString *jsonDict = [self convertToJsonData:tokenPara];
  110. NSString *callBacKMethod = [NSString stringWithFormat:@"%@('%@')",jsMethod,jsonDict];
  111. [self.webView evaluateJavaScript:callBacKMethod completionHandler:^(id _Nullable value, NSError * _Nullable error) {
  112. }];
  113. }
  114. /**
  115. 传token给js
  116. */
  117. - (void)sendUserTokenToJS:(WKScriptMessage *)message {
  118. __block NSString *token = [AccountTool account].token;
  119. NSDictionary *dict = [self dictionaryWithJsonString:message.body];
  120. NSString *jsMethod = dict[@"js_callback"];
  121. if (!token) {
  122. token = @"";
  123. }
  124. NSDictionary *tokenPara = @{@"token":token};
  125. NSString *jsonDict = [self convertToJsonData:tokenPara];
  126. NSString *callBacKMethod = [NSString stringWithFormat:@"%@('%@')",jsMethod,jsonDict];
  127. [self.webView evaluateJavaScript:callBacKMethod completionHandler:^(id _Nullable value, NSError * _Nullable error) {
  128. }];
  129. }
  130. - (void)loadRequest {
  131. if (@available(iOS 9.0, *)) {
  132. NSArray * types=@[WKWebsiteDataTypeCookies,WKWebsiteDataTypeLocalStorage];
  133. NSSet *websiteDataTypes= [NSSet setWithArray:types];
  134. NSDate *dateFrom = [NSDate dateWithTimeIntervalSince1970:0];
  135. [[WKWebsiteDataStore defaultDataStore] removeDataOfTypes:websiteDataTypes modifiedSince:dateFrom completionHandler:^{
  136. }];
  137. }
  138. // NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:self.url]];
  139. NSString *urlStr = [self.url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
  140. NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlStr]
  141. cachePolicy:NSURLRequestReloadIgnoringCacheData
  142. timeoutInterval:15.0];
  143. [self.webView loadRequest:theRequest];
  144. }
  145. - (void)viewWillAppear:(BOOL)animated {
  146. [super viewWillAppear:animated];
  147. self.navBar.navTitleLabel.textColor = [UIColor whiteColor];
  148. [self.navBar setNavTitle:self.webView.title];
  149. }
  150. - (void)refreshH5Action {
  151. if (@available(iOS 9.0, *)) {
  152. NSArray * types=@[WKWebsiteDataTypeCookies,WKWebsiteDataTypeLocalStorage];
  153. NSSet *websiteDataTypes= [NSSet setWithArray:types];
  154. NSDate *dateFrom = [NSDate dateWithTimeIntervalSince1970:0];
  155. [[WKWebsiteDataStore defaultDataStore] removeDataOfTypes:websiteDataTypes modifiedSince:dateFrom completionHandler:^{
  156. }];
  157. }
  158. NSString *callBacKMethod = [NSString stringWithFormat:@"%@()",refresh_h5];
  159. [self.webView evaluateJavaScript:callBacKMethod completionHandler:^(id _Nullable value, NSError * _Nullable error) {
  160. }];
  161. }
  162. /**
  163. kvo监听进度条
  164. @param keyPath keyPath description
  165. @param object object description
  166. @param change change description
  167. @param context context description
  168. */
  169. - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context{
  170. if ([keyPath isEqualToString:NSStringFromSelector(@selector(estimatedProgress))] && object == self.webView ) {
  171. [self.progressView setAlpha:1.0];
  172. [self.progressView setProgress:self.webView.estimatedProgress ];
  173. if (self.webView.estimatedProgress >= 1.0) {
  174. [UIView animateWithDuration:0.7 animations:^{
  175. [self.progressView setProgress:1.0 animated:YES];
  176. [self.progressView setAlpha:0.0];
  177. }];
  178. }
  179. }else{
  180. [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
  181. }
  182. }
  183. /**
  184. 当网页加载完成的时候调用
  185. @param webView web描述
  186. @param navigation 导航的描述
  187. */
  188. - (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{
  189. [self.navBar setNavTitle:self.webView.title];
  190. [[UIApplication sharedApplication]setNetworkActivityIndicatorVisible:NO];
  191. [self updateNavigationBarButtons];
  192. [self.webView.scrollView.mj_header endRefreshing];
  193. }
  194. #pragma mark- WKNavigationDelegate delegate
  195. /**
  196. 开始加载web的时候
  197. @param webView webView description
  198. @param navigation navigation description
  199. */
  200. - (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation{
  201. //开始加载的时候,让进度条显示
  202. self.progressView.hidden = NO;
  203. self.progressView.progress = 0;
  204. self.progressView.alpha = 1.0;
  205. [UIView animateWithDuration:0.8 animations:^{
  206. self.progressView.progress = 0.6;
  207. }];
  208. }
  209. -(void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler
  210. {
  211. NSURL *url = navigationAction.request.URL;
  212. UIApplication *app = [UIApplication sharedApplication];
  213. // 打开appstore
  214. if ([url.absoluteString containsString:@"https://itunes.apple.com/cn/app/"])
  215. {
  216. if ([app canOpenURL:url])
  217. {
  218. //设备系统为IOS 10.0或者以上的
  219. if (@available(iOS 10.0, *)) {
  220. [[UIApplication sharedApplication] openURL:url options:@{} completionHandler:nil];
  221. } else {
  222. [[UIApplication sharedApplication] openURL:url];
  223. }
  224. decisionHandler(WKNavigationActionPolicyCancel);
  225. return;
  226. }
  227. }
  228. decisionHandler(WKNavigationActionPolicyAllow);
  229. }
  230. - (WKWebView *)webView{
  231. if (!_webView) {
  232. WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
  233. config.allowsInlineMediaPlayback = NO;
  234. _webView = [[WKWebView alloc]initWithFrame:CGRectMake(0, NavBarHeight, SCREEN_WIDTH, SCREEN_HEIGHT-NavBarHeight-SafeBottomHeight) configuration:config];
  235. _webView.backgroundColor = [UIColor colorWithRed:240.0/255 green:240.0/255 blue:240.0/255 alpha:1.0];
  236. _webView.navigationDelegate = self;
  237. _webView.UIDelegate = self;
  238. //使用kvo监听进度
  239. [_webView addObserver:self forKeyPath:NSStringFromSelector(@selector(estimatedProgress)) options:0 context:nil];
  240. //手势触摸滑动
  241. _webView.allowsBackForwardNavigationGestures = YES;
  242. //自适应
  243. [_webView sizeToFit];
  244. }
  245. return _webView;
  246. }
  247. #pragma mark-
  248. #pragma mark- SetupConstraints
  249. /** 加载配置以及视图添加*/
  250. - (void)loadSubViewsConfiguration{
  251. [self.view addSubview:self.webView];
  252. }
  253. - (UIButton *)backButton {
  254. if (!_backButton) {
  255. _backButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 40, 40)];
  256. [_backButton setImage:[UIImage imageNamed:@"back"] forState:UIControlStateNormal];
  257. [_backButton addTarget:self action:@selector(backAction) forControlEvents:UIControlEventTouchUpInside];
  258. }
  259. return _backButton;
  260. }
  261. - (UIButton *)closeButton {
  262. if (!_closeButton) {
  263. _closeButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 40, 40)];
  264. [_closeButton setImage:[UIImage imageNamed:@"close_web"] forState:UIControlStateNormal];
  265. [_closeButton addTarget:self action:@selector(closeAction) forControlEvents:UIControlEventTouchUpInside];
  266. }
  267. return _closeButton;
  268. }
  269. - (UIButton *)refreshButton {
  270. if (!_refreshButton) {
  271. _refreshButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 40, 40)];
  272. [_refreshButton setImage:[UIImage imageNamed:@"icon_web_refresh"] forState:UIControlStateNormal];
  273. [_refreshButton addTarget:self action:@selector(refreshAction) forControlEvents:UIControlEventTouchUpInside];
  274. _refreshButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 40, 40)];
  275. }
  276. return _refreshButton;
  277. }
  278. - (void)backAction {
  279. NSArray *viewControllers = self.navigationController.viewControllers;
  280. if (viewControllers.count < 1){
  281. [self dismissViewControllerAnimated:YES completion:nil];
  282. }else {
  283. if (self.webView.canGoBack) {
  284. [self.webView goBack];
  285. }else{
  286. [self.navigationController popViewControllerAnimated:YES];
  287. }
  288. }
  289. }
  290. #pragma mark -----------
  291. - (void)updateNavigationBarButtons {
  292. if (self.webView.canGoBack) {
  293. [self.navBar setCustomLeftButtons:@[self.backButton,self.closeButton]];
  294. }else {
  295. [self.navBar setCustomLeftButtons:@[self.backButton]];
  296. }
  297. }
  298. - (void)closeAction {
  299. [self.navigationController popViewControllerAnimated:YES];
  300. }
  301. - (void)refreshAction {
  302. [self.webView reload];
  303. }
  304. - (UIProgressView *)progressView{
  305. if (!_progressView) {
  306. _progressView = [[UIProgressView alloc]initWithProgressViewStyle:UIProgressViewStyleDefault];
  307. _progressView.frame = CGRectMake(0, NavBarHeight, self.view.frame.size.width, 2);
  308. //设置进度条的色彩
  309. [_progressView setTrackTintColor:[UIColor colorWithRed:240.0/255 green:240.0/255 blue:240.0/255 alpha:1.0]];
  310. _progressView.progressTintColor = [UIColor homeRedColor];
  311. }
  312. return _progressView;
  313. }
  314. //观察的移除
  315. - (void)dealloc{
  316. [self.webView removeObserver:self forKeyPath:NSStringFromSelector(@selector(estimatedProgress))];
  317. [[NSNotificationCenter defaultCenter] removeObserver:self];
  318. }
  319. /**
  320. json字符串转字典
  321. */
  322. - (NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString
  323. {
  324. if (jsonString == nil) {
  325. return nil;
  326. }
  327. NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
  328. NSError *err;
  329. NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
  330. options:NSJSONReadingMutableContainers
  331. error:&err];
  332. if(err)
  333. {
  334. NSLog(@"json解析失败:%@",err);
  335. return nil;
  336. }
  337. return dic;
  338. }
  339. /**
  340. 字典转json字符串
  341. */
  342. - (NSString *)convertToJsonData:(NSDictionary *)dict
  343. {
  344. NSError *error;
  345. NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];
  346. NSString *jsonString;
  347. if (!jsonData) {
  348. NSLog(@"%@",error);
  349. }else{
  350. jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
  351. }
  352. NSMutableString *mutStr = [NSMutableString stringWithString:jsonString];
  353. NSRange range = {0,jsonString.length};
  354. //去掉字符串中的空格
  355. [mutStr replaceOccurrencesOfString:@" " withString:@"" options:NSLiteralSearch range:range];
  356. NSRange range2 = {0,mutStr.length};
  357. //去掉字符串中的换行符
  358. [mutStr replaceOccurrencesOfString:@"\n" withString:@"" options:NSLiteralSearch range:range2];
  359. return mutStr;
  360. }
  361. @end