酷店

KDPWebInteractionVC.m 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418
  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. if ([dict[@"commissionRate"]floatValue]>0) {
  89. model.commission_rate= [NSString stringWithFormat:@"%@",dict[@"commissionRate"]];
  90. }
  91. KDPGoodDetailVC *detailVC = [[KDPGoodDetailVC alloc] init];
  92. detailVC.model = model;
  93. [self.navigationController pushViewController:detailVC animated:YES];
  94. }
  95. -(void)getGoodDetail:(WKScriptMessage *)message
  96. {
  97. NSDictionary *dict = [KDPublicMethod dictionaryWithJsonString:message.body];
  98. KDPGoodsModel *model =[[KDPGoodsModel alloc]init];
  99. model.goods_id = [NSString stringWithFormat:@"%@",dict[@"goodsId"]];
  100. if ([dict[@"commissionRate"]floatValue]>0) {
  101. model.commission_rate= [NSString stringWithFormat:@"%@",dict[@"commissionRate"]];
  102. }
  103. KDPGoodDetailVC *detailVC = [[KDPGoodDetailVC alloc] init];
  104. detailVC.model = model;
  105. [self.navigationController pushViewController:detailVC animated:YES];
  106. }
  107. #pragma mark---保存本地
  108. -(void)saveLocal:(WKScriptMessage *)message
  109. {
  110. NSLog(@"%@",message.body);
  111. NSDictionary *dic =[KDPublicMethod dictionaryWithJsonString:message.body];
  112. [KDPublicMethod saveMessage:dic];
  113. }
  114. /**
  115. 传消息给js
  116. */
  117. - (void)sendmessageToJS:(WKScriptMessage *)message {
  118. NSDictionary *dict = [KDPublicMethod dictionaryWithJsonString:message.body];
  119. NSString *jsMethod = dict[@"js_callback"];
  120. NSDictionary *tokenPara = [KDPublicMethod getMessage];
  121. if (tokenPara.allKeys.count == 0) {
  122. return;
  123. }
  124. NSString *jsonDict = [KDPublicMethod convertToJsonData:tokenPara];
  125. NSString *callBacKMethod = [NSString stringWithFormat:@"%@('%@')",jsMethod,jsonDict];
  126. [self.webInterView evaluateJavaScript:callBacKMethod completionHandler:^(id _Nullable value, NSError * _Nullable error) {
  127. }];
  128. }
  129. /**
  130. 传token给js
  131. */
  132. - (void)sendUserTokenToJS:(WKScriptMessage *)message {
  133. __block NSString *token = [KDPAccountTool account].token;
  134. NSDictionary *dict = [KDPublicMethod dictionaryWithJsonString:message.body];
  135. NSString *jsMethod = dict[@"js_callback"];
  136. if (!token) {
  137. token = @"";
  138. }
  139. NSDictionary *tokenPara = @{@"token":token};
  140. NSString *jsonDict = [KDPublicMethod convertToJsonData:tokenPara];
  141. NSString *callBacKMethod = [NSString stringWithFormat:@"%@('%@')",jsMethod,jsonDict];
  142. [self.webInterView evaluateJavaScript:callBacKMethod completionHandler:^(id _Nullable value, NSError * _Nullable error) {
  143. }];
  144. }
  145. - (void)loadRequest {
  146. if (@available(iOS 9.0, *)) {
  147. NSArray * types=@[WKWebsiteDataTypeCookies,WKWebsiteDataTypeLocalStorage];
  148. NSSet *websiteDataTypes= [NSSet setWithArray:types];
  149. NSDate *dateFrom = [NSDate dateWithTimeIntervalSince1970:0];
  150. [[WKWebsiteDataStore defaultDataStore] removeDataOfTypes:websiteDataTypes modifiedSince:dateFrom completionHandler:^{
  151. }];
  152. }
  153. // NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:self.url]];
  154. NSString *urlStr = [self.url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
  155. NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlStr]
  156. cachePolicy:NSURLRequestReloadIgnoringCacheData
  157. timeoutInterval:15.0];
  158. [self.webInterView loadRequest:theRequest];
  159. }
  160. - (void)viewWillAppear:(BOOL)animated {
  161. [super viewWillAppear:animated];
  162. self.tabBarController.tabBar.hidden=YES;
  163. self.navBar.navTitleLabel.textColor = [UIColor whiteColor];
  164. self.navBar.navTitleLabel.text=self.webInterView.title;
  165. }
  166. - (void)updateSelectorWithH5 {
  167. if (@available(iOS 9.0, *)) {
  168. NSArray * types=@[WKWebsiteDataTypeCookies,WKWebsiteDataTypeLocalStorage];
  169. NSSet *websiteDataTypes= [NSSet setWithArray:types];
  170. NSDate *dateFrom = [NSDate dateWithTimeIntervalSince1970:0];
  171. [[WKWebsiteDataStore defaultDataStore] removeDataOfTypes:websiteDataTypes modifiedSince:dateFrom completionHandler:^{
  172. }];
  173. }
  174. NSString *callBacKMethod = [NSString stringWithFormat:@"%@()",refresh_h5];
  175. [self.webInterView evaluateJavaScript:callBacKMethod completionHandler:^(id _Nullable value, NSError * _Nullable error) {
  176. }];
  177. }
  178. /**
  179. kvo监听进度条
  180. @param keyPath keyPath description
  181. @param object object description
  182. @param change change description
  183. @param context context description
  184. */
  185. - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context{
  186. if ([keyPath isEqualToString:NSStringFromSelector(@selector(estimatedProgress))] && object == self.webInterView ) {
  187. [self.progressView setAlpha:1.0];
  188. [self.progressView setProgress:self.webInterView.estimatedProgress ];
  189. if (self.webInterView.estimatedProgress >= 1.0) {
  190. [UIView animateWithDuration:0.7 animations:^{
  191. [self.progressView setProgress:1.0 animated:YES];
  192. [self.progressView setAlpha:0.0];
  193. }];
  194. }
  195. }else{
  196. [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
  197. }
  198. }
  199. - (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{
  200. self.navBar.navTitleLabel.text=self.webInterView.title;
  201. [[UIApplication sharedApplication]setNetworkActivityIndicatorVisible:NO];
  202. [self updateNavigationBarButtons];
  203. [self.webInterView.scrollView.mj_header endRefreshing];
  204. }
  205. #pragma mark- WKNavigationDelegate delegate
  206. /**
  207. 开始加载web的时候
  208. @param webView webView description
  209. @param navigation navigation description
  210. */
  211. - (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation{
  212. //开始加载的时候,让进度条显示
  213. self.progressView.hidden = NO;
  214. self.progressView.progress = 0;
  215. self.progressView.alpha = 1.0;
  216. self.navBar.navTitleLabel.text=webView.title;
  217. [UIView animateWithDuration:0.8 animations:^{
  218. self.progressView.progress = 0.6;
  219. }];
  220. self.navBar.navTitleLabel.text=self.webInterView.title;
  221. }
  222. -(void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler
  223. {
  224. NSURL *url = navigationAction.request.URL;
  225. UIApplication *app = [UIApplication sharedApplication];
  226. // 打开appstore
  227. if ([url.absoluteString containsString:@"https://itunes.apple.com/cn/app/"])
  228. {
  229. if ([app canOpenURL:url])
  230. {
  231. //设备系统为IOS 10.0或者以上的
  232. if (@available(iOS 10.0, *)) {
  233. [[UIApplication sharedApplication] openURL:url options:@{} completionHandler:nil];
  234. } else {
  235. [[UIApplication sharedApplication] openURL:url];
  236. }
  237. decisionHandler(WKNavigationActionPolicyCancel);
  238. return;
  239. }
  240. }
  241. decisionHandler(WKNavigationActionPolicyAllow);
  242. }
  243. - (WKWebView *)webInterView{
  244. if (!_webInterView) {
  245. WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
  246. config.allowsInlineMediaPlayback = NO;
  247. _webInterView = [[WKWebView alloc]initWithFrame:CGRectMake(0, KDNavBarHeight, SCREEN_WIDTH, SCREEN_HEIGHT-KDNavBarHeight-KDTabBottomHeight) configuration:config];
  248. //使用kvo监听进度
  249. [_webInterView addObserver:self forKeyPath:NSStringFromSelector(@selector(estimatedProgress)) options:0 context:nil];
  250. _webInterView.backgroundColor = [UIColor colorWithRed:240.0/255 green:240.0/255 blue:240.0/255 alpha:1.0];
  251. _webInterView.UIDelegate = self;
  252. _webInterView.navigationDelegate = self;
  253. //手势触摸滑动
  254. _webInterView.allowsBackForwardNavigationGestures = YES;
  255. //自适应
  256. [_webInterView sizeToFit];
  257. }
  258. return _webInterView;
  259. }
  260. #pragma mark-
  261. #pragma mark- SetupConstraints
  262. /** 加载配置以及视图添加*/
  263. - (void)loadSubViewsConfiguration{
  264. [self.view addSubview:self.webInterView];
  265. }
  266. - (UIButton *)returnBtn {
  267. if (!_returnBtn) {
  268. _returnBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 40, 40)];
  269. [_returnBtn setImage:[UIImage imageNamed:@"back"] forState:UIControlStateNormal];
  270. [_returnBtn addTarget:self action:@selector(backAction) forControlEvents:UIControlEventTouchUpInside];
  271. }
  272. return _returnBtn;
  273. }
  274. - (UIButton *)closeButton {
  275. if (!_closeButton) {
  276. _closeButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 40, 40)];
  277. [_closeButton setImage:[UIImage imageNamed:@"close_web"] forState:UIControlStateNormal];
  278. [_closeButton addTarget:self action:@selector(closeAction) forControlEvents:UIControlEventTouchUpInside];
  279. }
  280. return _closeButton;
  281. }
  282. - (UIButton *)refreshButton {
  283. if (!_refreshButton) {
  284. _refreshButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 40, 40)];
  285. [_refreshButton setImage:[UIImage imageNamed:@"icon_web_refresh"] forState:UIControlStateNormal];
  286. [_refreshButton addTarget:self action:@selector(refreshAction) forControlEvents:UIControlEventTouchUpInside];
  287. _refreshButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 40, 40)];
  288. }
  289. return _refreshButton;
  290. }
  291. - (void)backAction {
  292. NSArray *viewControllers = self.navigationController.viewControllers;
  293. if (viewControllers.count < 1){
  294. [self dismissViewControllerAnimated:YES completion:nil];
  295. }else {
  296. if (self.webInterView.canGoBack) {
  297. [self.webInterView goBack];
  298. }else{
  299. [self.navigationController popViewControllerAnimated:YES];
  300. }
  301. }
  302. }
  303. #pragma mark -----------
  304. - (void)updateNavigationBarButtons {
  305. }
  306. - (void)closeAction {
  307. [self.navigationController popViewControllerAnimated:YES];
  308. }
  309. - (void)refreshAction {
  310. [self.webInterView reload];
  311. }
  312. - (UIProgressView *)progressView{
  313. if (!_progressView) {
  314. _progressView = [[UIProgressView alloc]initWithProgressViewStyle:UIProgressViewStyleDefault];
  315. _progressView.frame = CGRectMake(0, KDNavBarHeight, self.view.frame.size.width, 2);
  316. //设置进度条的色彩
  317. [_progressView setTrackTintColor:[UIColor colorWithRed:240.0/255 green:240.0/255 blue:240.0/255 alpha:1.0]];
  318. _progressView.progressTintColor = [UIColor colorWithHexString:ThemeColor];
  319. }
  320. return _progressView;
  321. }
  322. //观察的移除
  323. - (void)dealloc{
  324. [self.webInterView removeObserver:self forKeyPath:NSStringFromSelector(@selector(estimatedProgress))];
  325. [[NSNotificationCenter defaultCenter] removeObserver:self];
  326. }
  327. @end