酷店

KDPWebInteractionVC.m 14KB

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