猎豆优选

LDAdWebViewController.m 35KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902
  1. //
  2. // LDAdWebViewController.m
  3. // YouHuiProject
  4. //
  5. // Created by 小花 on 2018/2/5.
  6. // Copyright © 2018年 kuxuan. All rights reserved.
  7. //
  8. #import "LDAdWebViewController.h"
  9. #import <AlibcTradeSDK/AlibcTradeSDK.h>
  10. #import <AlibabaAuthSDK/ALBBSession.h>
  11. #import <AlibabaAuthSDK/ALBBSDK.h>
  12. #import <WebKit/WebKit.h>
  13. #import "WebviewProgressLine.h"
  14. #import <JavaScriptCore/JavaScriptCore.h>
  15. #import "LDFeedbackController.h"
  16. #import "WechatShareTool.h"
  17. #import "WYWeakScriptMessageDelegate.h"
  18. #import "LDLoginViewController.h"
  19. #import "LDChildAccountViewController.h"
  20. #import <MJRefresh/UIScrollView+MJRefresh.h>
  21. static NSString *app_h5_close = @"app_h5_close";
  22. static NSString *app_h5_get_token = @"app_h5_get_token";
  23. static NSString *app_h5_wx_share = @"app_h5_wx_share";
  24. static NSString *app_h5_get_wechat_info = @"app_h5_get_wechat_info";
  25. static NSString *refresh_h5 = @"refresh_h5";
  26. static NSString *app_h5_login = @"app_h5_login"; //h5唤起原生的登录
  27. static NSString *app_h5_wx_share_url = @"app_h5_wx_share_url"; //分享url
  28. static NSString *app_h5_wx_share_image = @"app_h5_wx_share_image"; //分享到微信image
  29. static NSString *app_h5_wx_share_video = @"app_h5_wx_share_video"; //分享到微信video
  30. static NSString *app_h5_wx_share_min = @"app_h5_wx_share_min"; //分享微信小程序(只支持微信好友)
  31. static NSString *app_h5_open_taobao_url = @"app_h5_open_taobao_url"; //打开淘宝url
  32. static NSString *app_h5_open_goodDetail =@"app_h5_open_goodDetail";//唤起原生的详情页
  33. static NSString *app_h5_open_url =@"app_h5_open_url";//h5打开URL
  34. static NSString *app_h5_isLogin =@"app_h5_isLogin";//是否登录
  35. static NSString *app_h5_withdraw =@"app_h5_withdraw";//提现页面
  36. static NSString *openWeiChat =@"openWeiChat";//打开微信
  37. static NSString *app_h5_getDeviceInfo=@"app_h5_getDeviceInfo";//h5获取手机信息
  38. @interface LDAdWebViewController ()<WKUIDelegate, WKNavigationDelegate,WKScriptMessageHandler>
  39. @property (nonatomic, strong) WKWebView *webView;
  40. /** 加载进度条 */
  41. @property (nonatomic, strong) UIProgressView *progressView;
  42. @property (nonatomic, strong) UIButton *backButton;
  43. @property (nonatomic, strong) UIButton *closeButton;
  44. @property (nonatomic, strong) UIButton *refreshButton;
  45. @end
  46. @implementation LDAdWebViewController
  47. - (void)viewDidAppear:(BOOL)animated {
  48. [super viewDidAppear:animated];
  49. if ([_redStr isEqualToString:@"红包"]) {
  50. [_backButton setImage:nil forState:UIControlStateNormal];
  51. self.navigationBar.backgroundColor = [UIColor changeColor];
  52. self.navigationBar.showNavigationBarBottomLine = NO;
  53. [self.navigationBar setNavTitle:@"红包"];
  54. self.navigationBar.navTitleLabel.textColor = [UIColor whiteColor];
  55. [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
  56. }else{
  57. [_backButton setImage:[UIImage imageNamed:@"back"] forState:UIControlStateNormal];
  58. self.navigationBar.backgroundColor = [UIColor clearColor];
  59. [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault];
  60. }
  61. }
  62. -(void)requestTabbar
  63. {
  64. [LDHttp post:[NSString stringWithFormat:@"%@/api/v2/redactive/redNewUrl",BaseURL] params:nil success:^(id json) {
  65. if ([[PhoneLoginManager shareManager].showPhoneBtn boolValue]) {
  66. self.url =[NSString stringWithFormat:@"%@?speical=true",json[@"data"][@"url"]];
  67. }else{
  68. self.url=json[@"data"][@"url"];
  69. }
  70. [self loadRequest];
  71. } failure:^(NSError *error) {
  72. }];
  73. }
  74. - (void)viewWillAppear:(BOOL)animated {
  75. [super viewWillAppear:animated];
  76. self.navigationBar.navTitleLabel.textColor = [UIColor whiteColor];
  77. [MobClick event:RedTabbar label:@"红包tabbar"];
  78. }
  79. - (void)viewDidLoad {
  80. [super viewDidLoad];
  81. self.navigationController.navigationBar.hidden = YES;
  82. [self addNotification];
  83. [self configNavigationBar];
  84. [self addUserhandler];
  85. [self loadRequest];
  86. if ([_redStr isEqualToString:@"红包"]) {
  87. [self requestTabbar];
  88. }
  89. }
  90. - (void)addNotification {
  91. [[NSNotificationCenter defaultCenter] addObserver:self
  92. selector:@selector(refreshH5Action)
  93. name:UIApplicationDidBecomeActiveNotification object:nil];
  94. [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(endFullScreen) name:UIWindowDidBecomeHiddenNotification object:nil];
  95. }
  96. //处理web视频全屏播放时 状态栏消失
  97. - (void)endFullScreen {
  98. [[UIApplication sharedApplication]setStatusBarHidden:false animated:false];
  99. }
  100. - (void)configNavigationBar {
  101. self.view.backgroundColor = [UIColor whiteColor];
  102. [self.view addSubview:self.webView];
  103. [self.view addSubview:self.progressView];
  104. self.navigationBar.showNavigationBarBottomLine = YES;
  105. [self.navigationBar setCustomLeftButtons:@[self.backButton]];
  106. [self.navigationBar setCustomRightButtons:@[self.refreshButton]];
  107. if (@available(iOS 11.0, *)) {
  108. self.webView.scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;//UIScrollView也适用
  109. }else {
  110. self.automaticallyAdjustsScrollViewInsets = NO;
  111. }
  112. }
  113. - (void)loadRequest {
  114. if (@available(iOS 9.0, *)) {
  115. NSArray * types=@[WKWebsiteDataTypeCookies,WKWebsiteDataTypeLocalStorage];
  116. NSSet *websiteDataTypes= [NSSet setWithArray:types];
  117. NSDate *dateFrom = [NSDate dateWithTimeIntervalSince1970:0];
  118. [[WKWebsiteDataStore defaultDataStore] removeDataOfTypes:websiteDataTypes modifiedSince:dateFrom completionHandler:^{
  119. }];
  120. }
  121. // NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:self.url]];
  122. NSString *urlStr = [self.url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
  123. NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlStr]
  124. cachePolicy:NSURLRequestReloadIgnoringCacheData
  125. timeoutInterval:15.0];
  126. [self.webView loadRequest:theRequest];
  127. }
  128. - (void)addUserhandler {
  129. [[self.webView configuration].userContentController addScriptMessageHandler:[[WYWeakScriptMessageDelegate alloc] initWithDelegate:self] name:app_h5_close];
  130. [[self.webView configuration].userContentController addScriptMessageHandler:[[WYWeakScriptMessageDelegate alloc] initWithDelegate:self] name:app_h5_get_token];
  131. [[self.webView configuration].userContentController addScriptMessageHandler:[[WYWeakScriptMessageDelegate alloc] initWithDelegate:self] name:app_h5_wx_share];
  132. [[self.webView configuration].userContentController addScriptMessageHandler:[[WYWeakScriptMessageDelegate alloc] initWithDelegate:self] name:app_h5_get_wechat_info];
  133. [[self.webView configuration].userContentController addScriptMessageHandler:[[WYWeakScriptMessageDelegate alloc] initWithDelegate:self] name:app_h5_login];
  134. [[self.webView configuration].userContentController addScriptMessageHandler:[[WYWeakScriptMessageDelegate alloc] initWithDelegate:self] name:app_h5_wx_share_url];
  135. [[self.webView configuration].userContentController addScriptMessageHandler:[[WYWeakScriptMessageDelegate alloc] initWithDelegate:self] name:app_h5_wx_share_image];
  136. [[self.webView configuration].userContentController addScriptMessageHandler:[[WYWeakScriptMessageDelegate alloc] initWithDelegate:self] name:app_h5_wx_share_video];
  137. [[self.webView configuration].userContentController addScriptMessageHandler:[[WYWeakScriptMessageDelegate alloc] initWithDelegate:self] name:app_h5_wx_share_min];
  138. [[self.webView configuration].userContentController addScriptMessageHandler:[[WYWeakScriptMessageDelegate alloc] initWithDelegate:self] name:app_h5_open_taobao_url];
  139. [[self.webView configuration].userContentController addScriptMessageHandler:[[WYWeakScriptMessageDelegate alloc] initWithDelegate:self] name:app_h5_open_goodDetail];
  140. [[self.webView configuration].userContentController addScriptMessageHandler:[[WYWeakScriptMessageDelegate alloc] initWithDelegate:self] name:app_h5_open_url];
  141. [[self.webView configuration].userContentController addScriptMessageHandler:[[WYWeakScriptMessageDelegate alloc] initWithDelegate:self] name:app_h5_isLogin];
  142. [[self.webView configuration].userContentController addScriptMessageHandler:[[WYWeakScriptMessageDelegate alloc] initWithDelegate:self] name:app_h5_withdraw];
  143. [[self.webView configuration].userContentController addScriptMessageHandler:[[WYWeakScriptMessageDelegate alloc] initWithDelegate:self] name:openWeiChat];
  144. [[self.webView configuration].userContentController addScriptMessageHandler:[[WYWeakScriptMessageDelegate alloc] initWithDelegate:self] name:app_h5_getDeviceInfo];
  145. }
  146. #pragma mark --- WKScriptMessageHandler
  147. - (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
  148. if ([message.name isEqualToString:app_h5_close]) {
  149. //关闭页面
  150. [self.navigationController popViewControllerAnimated:YES];
  151. }
  152. else if ([message.name isEqualToString:app_h5_get_token]){
  153. //传token给js
  154. [self sendUserTokenToJS:message];
  155. }
  156. else if ([message.name isEqualToString:app_h5_wx_share]){
  157. //调起原生分享
  158. [self shareToNative:message];
  159. }
  160. else if ([message.name isEqualToString:app_h5_get_wechat_info]){
  161. //获取微信信息
  162. [self getWechatInfoWithMessage:message];
  163. }
  164. else if ([message.name isEqualToString:app_h5_wx_share_image]){
  165. //分享图片
  166. [self shareImage:message];
  167. }
  168. else if ([message.name isEqualToString:app_h5_wx_share_url]){
  169. //分享url
  170. [self shareURL:message];
  171. }
  172. else if ([message.name isEqualToString:app_h5_wx_share_video]){
  173. //分享video
  174. [self shareVideo:message];
  175. }
  176. else if ([message.name isEqualToString:app_h5_wx_share_min]){
  177. //分享小程序
  178. [self shareMinProgram:message];
  179. }else if ([message.name isEqualToString:app_h5_login]){
  180. //获取token
  181. [self gotoNativeLogin:message];
  182. }else if ([message.name isEqualToString:app_h5_open_taobao_url]){
  183. //打开淘宝
  184. [self openTaobao:message];
  185. }else if ([message.name isEqualToString:app_h5_open_goodDetail] )
  186. {
  187. [self goodDetail:message];
  188. }else if ([message.name isEqualToString:app_h5_open_url] )
  189. {//h5打开URL
  190. [self openUrl:message];
  191. }else if ([message.name isEqualToString:app_h5_isLogin] )
  192. {
  193. [self sendUserTokenISLoginToJS:message];
  194. }else if ([message.name isEqualToString:app_h5_withdraw] )//提现
  195. {
  196. [self withdrawal:message];
  197. }else if ([message.name isEqualToString:openWeiChat] )//打开微信
  198. {
  199. [self callWeChat];
  200. }else if ([message.name isEqualToString:app_h5_getDeviceInfo] )//获取手机信息
  201. {
  202. [self getDeviceInfo:message];
  203. }
  204. else {
  205. }
  206. }
  207. //调起微信
  208. - (void)callWeChat
  209. {
  210. NSString* WeChatUrl = [NSString stringWithFormat:@"weixin://"];
  211. UIWebView* webview = [[UIWebView alloc]initWithFrame:CGRectZero];
  212. [[UIApplication sharedApplication].keyWindow addSubview:webview];
  213. NSURL*url = [NSURL URLWithString:WeChatUrl];
  214. NSURLRequest *request = [NSURLRequest requestWithURL:url];
  215. [webview loadRequest:request];
  216. }
  217. //h5打开URL
  218. -(void)openUrl:(WKScriptMessage *)message
  219. {
  220. NSDictionary *dict = [self dictionaryWithJsonString:message.body];
  221. NSString *jsMethod = dict[@"push_url"];
  222. LDAdWebViewController *web =[[LDAdWebViewController alloc]init];
  223. web.url=jsMethod;
  224. [self.navigationController pushViewController:web animated:YES];
  225. }
  226. /**
  227. 传token判断登录给js
  228. */
  229. - (void)sendUserTokenISLoginToJS:(WKScriptMessage *)message {
  230. __block NSString *token = [AccountTool account].token;
  231. NSDictionary *dict = [self dictionaryWithJsonString:message.body];
  232. NSString *jsMethod = dict[@"js_callback"];
  233. if (!token) {
  234. token = @"";
  235. }
  236. NSString *islogin=@"false";
  237. if ([AccountTool isLogin] ) {
  238. islogin = @"true";
  239. }
  240. NSDictionary *tokenPara = @{@"token":token,
  241. @"isLogin":islogin
  242. };
  243. NSString *jsonDict = [self convertToJsonData:tokenPara];
  244. NSString *callBacKMethod = [NSString stringWithFormat:@"%@('%@')",jsMethod,jsonDict];
  245. [self.webView evaluateJavaScript:callBacKMethod completionHandler:^(id _Nullable value, NSError * _Nullable error) {
  246. }];
  247. }
  248. - (void)refreshH5Action {
  249. if (@available(iOS 9.0, *)) {
  250. NSArray * types=@[WKWebsiteDataTypeCookies,WKWebsiteDataTypeLocalStorage];
  251. NSSet *websiteDataTypes= [NSSet setWithArray:types];
  252. NSDate *dateFrom = [NSDate dateWithTimeIntervalSince1970:0];
  253. [[WKWebsiteDataStore defaultDataStore] removeDataOfTypes:websiteDataTypes modifiedSince:dateFrom completionHandler:^{
  254. }];
  255. }
  256. NSString *callBacKMethod = [NSString stringWithFormat:@"%@()",refresh_h5];
  257. [self.webView evaluateJavaScript:callBacKMethod completionHandler:^(id _Nullable value, NSError * _Nullable error) {
  258. }];
  259. }
  260. //提现页面
  261. -(void)withdrawal:(WKScriptMessage *)message
  262. {
  263. if (![AccountTool isLogin]) {
  264. LDNewLoginVC *login = [[LDNewLoginVC alloc] init];
  265. login.loginSucc = ^{
  266. NSDictionary *dict = [self dictionaryWithJsonString:message.body];
  267. NSString *jsMethod = dict[@"js_callback"];
  268. NSString *token = [AccountTool account].token;
  269. NSDictionary *param = @{@"token":token,
  270. };
  271. NSString *jsonDict = [self convertToJsonData:param];
  272. NSString *callBacKMethod = [NSString stringWithFormat:@"%@('%@')",jsMethod,jsonDict];
  273. [self.webView evaluateJavaScript:callBacKMethod completionHandler:^(id _Nullable value, NSError * _Nullable error) {
  274. }];
  275. };
  276. login.modalPresentationStyle = UIModalPresentationFullScreen;
  277. [self presentViewController:login animated:YES completion:nil];
  278. return;
  279. }
  280. LDChildAccountViewController *accountDetail = [[LDChildAccountViewController alloc] init];//提现
  281. [self.navigationController pushViewController:accountDetail animated:YES];
  282. }
  283. /**
  284. 传token给js
  285. */
  286. - (void)sendUserTokenToJS:(WKScriptMessage *)message {
  287. __block NSString *token = [AccountTool account].token;
  288. NSString *openid = [AccountTool account].openId;
  289. NSString *unionid = [AccountTool account].unionid;
  290. if (![AccountTool isLogin] || openid==nil || unionid ==nil) {
  291. LDNewLoginVC *login = [[LDNewLoginVC alloc] init];
  292. login.loginSucc = ^{
  293. NSDictionary *dict = [self dictionaryWithJsonString:message.body];
  294. NSString *jsMethod = dict[@"js_callback"];
  295. if (!token) {
  296. token = @"";
  297. }
  298. NSDictionary *tokenPara = @{@"token":token,
  299. @"openid":openid,
  300. @"unionid":unionid,
  301. };
  302. NSString *jsonDict = [self convertToJsonData:tokenPara];
  303. NSString *callBacKMethod = [NSString stringWithFormat:@"%@('%@')",jsMethod,jsonDict];
  304. [self.webView evaluateJavaScript:callBacKMethod completionHandler:^(id _Nullable value, NSError * _Nullable error) {
  305. }];
  306. };
  307. login.modalPresentationStyle = UIModalPresentationFullScreen;
  308. [self presentViewController:login animated:YES completion:nil];
  309. return;
  310. }
  311. NSDictionary *dict = [self dictionaryWithJsonString:message.body];
  312. NSString *jsMethod = dict[@"js_callback"];
  313. if (!token) {
  314. token = @"";
  315. }
  316. NSDictionary *tokenPara = @{@"token":token,
  317. @"openid":openid,
  318. @"unionid":unionid,
  319. };
  320. NSString *jsonDict = [self convertToJsonData:tokenPara];
  321. NSString *callBacKMethod = [NSString stringWithFormat:@"%@('%@')",jsMethod,jsonDict];
  322. [self.webView evaluateJavaScript:callBacKMethod completionHandler:^(id _Nullable value, NSError * _Nullable error) {
  323. }];
  324. }
  325. //商品详情页
  326. -(void)goodDetail:(WKScriptMessage *)message
  327. {
  328. NSDictionary *dict = [self dictionaryWithJsonString:message.body];
  329. DetailRequestModel *model =[[DetailRequestModel alloc]init];
  330. [model setValuesForKeysWithDictionary:dict];
  331. LDGoodDetailViewController *detail = [[LDGoodDetailViewController alloc] init];
  332. detail.requestModel = model;
  333. [self.navigationController pushViewController:detail animated:YES];
  334. }
  335. #pragma mark---获取手机信息
  336. -(void)getDeviceInfo:(WKScriptMessage *)message
  337. {
  338. NSDictionary *dict = [self dictionaryWithJsonString:message.body];
  339. NSString *jsMethod = dict[@"js_callback"];
  340. NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
  341. NSString *appVersion = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
  342. // build版本号
  343. NSString *appBuild = [infoDictionary objectForKey:@"CFBundleVersion"];
  344. NSDictionary *param = @{
  345. @"versionCode":appVersion,//版本号
  346. @"versionName":appBuild,//版本名
  347. @"deviceWidth":[NSString stringWithFormat:@"%.2f",SCREEN_WIDTH] ,//屏幕宽
  348. @"deviceHeight":[NSString stringWithFormat:@"%.2f",SCREEN_HEIGHT] ,//屏幕高
  349. @"deviceBrand":@"iPhone", //品牌
  350. @"deviceModel":[LDDeviceTools getCurrentDeviceModel], //型号
  351. @"deviceVersion":[[UIDevice currentDevice] systemVersion],// 版本
  352. };
  353. NSString *jsonDict = [self convertToJsonData:param];
  354. NSString *callBacKMethod = [NSString stringWithFormat:@"%@('%@')",jsMethod,jsonDict];
  355. [self.webView evaluateJavaScript:callBacKMethod completionHandler:^(id _Nullable value, NSError * _Nullable error) {
  356. }];
  357. }
  358. /**
  359. 唤起登录
  360. */
  361. - (void)gotoNativeLogin:(WKScriptMessage *)message {
  362. if (![AccountTool isLogin]) {
  363. LDNewLoginVC *login = [[LDNewLoginVC alloc] init];
  364. login.loginSucc = ^{
  365. NSDictionary *dict = [self dictionaryWithJsonString:message.body];
  366. NSString *jsMethod = dict[@"js_callback"];
  367. NSString *token = [AccountTool account].token;
  368. NSDictionary *param = @{@"token":token,
  369. };
  370. NSString *jsonDict = [self convertToJsonData:param];
  371. NSString *callBacKMethod = [NSString stringWithFormat:@"%@('%@')",jsMethod,jsonDict];
  372. [self.webView evaluateJavaScript:callBacKMethod completionHandler:^(id _Nullable value, NSError * _Nullable error) {
  373. }];
  374. };
  375. login.modalPresentationStyle = UIModalPresentationFullScreen;
  376. [self presentViewController:login animated:YES completion:nil];
  377. return;
  378. }
  379. NSDictionary *dict = [self dictionaryWithJsonString:message.body];
  380. NSString *jsMethod = dict[@"js_callback"];
  381. NSString *token = [AccountTool account].token;
  382. NSDictionary *param = @{@"token":token,
  383. };
  384. NSString *jsonDict = [self convertToJsonData:param];
  385. NSString *callBacKMethod = [NSString stringWithFormat:@"%@('%@')",jsMethod,jsonDict];
  386. [self.webView evaluateJavaScript:callBacKMethod completionHandler:^(id _Nullable value, NSError * _Nullable error) {
  387. }];
  388. }
  389. /**
  390. 获取微信信息
  391. */
  392. - (void)getWechatInfoWithMessage:(WKScriptMessage *)message {
  393. NSString *openid = [AccountTool account].openId;
  394. NSString *unionid = [AccountTool account].unionid;
  395. if (![AccountTool isLogin] || openid==nil || unionid ==nil) {
  396. LDNewLoginVC *login = [[LDNewLoginVC alloc] init];
  397. login.loginSucc = ^{
  398. NSDictionary *dict = [self dictionaryWithJsonString:message.body];
  399. NSString *jsMethod = dict[@"js_callback"];
  400. NSDictionary *param = @{@"openid":openid,
  401. @"unionid":unionid
  402. };
  403. NSString *jsonDict = [self convertToJsonData:param];
  404. NSString *callBacKMethod = [NSString stringWithFormat:@"%@('%@')",jsMethod,jsonDict];
  405. [self.webView evaluateJavaScript:callBacKMethod completionHandler:^(id _Nullable value, NSError * _Nullable error) {
  406. }];
  407. };
  408. login.modalPresentationStyle = UIModalPresentationFullScreen;
  409. [self presentViewController:login animated:YES completion:nil];
  410. return;
  411. }
  412. NSDictionary *dict = [self dictionaryWithJsonString:message.body];
  413. NSString *jsMethod = dict[@"js_callback"];
  414. NSDictionary *param = @{@"openid":openid,
  415. @"unionid":unionid
  416. };
  417. NSString *jsonDict = [self convertToJsonData:param];
  418. NSString *callBacKMethod = [NSString stringWithFormat:@"%@('%@')",jsMethod,jsonDict];
  419. [self.webView evaluateJavaScript:callBacKMethod completionHandler:^(id _Nullable value, NSError * _Nullable error) {
  420. }];
  421. }
  422. /**
  423. 调起分享
  424. */
  425. - (void)shareToNative:(WKScriptMessage *)message {
  426. NSDictionary *dict = [self dictionaryWithJsonString:message.body];
  427. if ([dict[@"shareType"] isEqualToString:@"1"]) {
  428. [self shareImageWithplatformType:UMSocialPlatformType_WechatSession withDict:dict];
  429. }else {
  430. [self shareImageWithplatformType:UMSocialPlatformType_WechatTimeLine withDict:dict];
  431. }
  432. }
  433. - (void)shareImage:(WKScriptMessage *)message {
  434. NSDictionary *dict = [self dictionaryWithJsonString:message.body];
  435. if ([dict[@"shareType"] isEqualToString:@"1"]) {
  436. [WechatShareTool shareImageWithplatformType:UMSocialPlatformType_WechatSession withDict:dict];
  437. }else {
  438. [WechatShareTool shareImageWithplatformType:UMSocialPlatformType_WechatTimeLine withDict:dict];
  439. }
  440. }
  441. - (void)shareURL:(WKScriptMessage *)message {
  442. NSDictionary *dict = [self dictionaryWithJsonString:message.body];
  443. if ([dict[@"shareType"] isEqualToString:@"1"]) {
  444. [WechatShareTool shareURLWithplatformType:UMSocialPlatformType_WechatSession withDict:dict];
  445. }else {
  446. [WechatShareTool shareURLWithplatformType:UMSocialPlatformType_WechatTimeLine withDict:dict];
  447. }
  448. }
  449. - (void)shareVideo:(WKScriptMessage *)message {
  450. NSDictionary *dict = [self dictionaryWithJsonString:message.body];
  451. if ([dict[@"shareType"] isEqualToString:@"1"]) {
  452. [WechatShareTool shareVideoWithplatformType:UMSocialPlatformType_WechatSession withDict:dict];
  453. }else {
  454. [WechatShareTool shareVideoWithplatformType:UMSocialPlatformType_WechatTimeLine withDict:dict];
  455. }
  456. }
  457. - (void)shareMinProgram:(WKScriptMessage *)message {
  458. NSDictionary *dict = [self dictionaryWithJsonString:message.body];
  459. [WechatShareTool shareMinProgramWithplatformType:UMSocialPlatformType_WechatSession withDict:dict];
  460. }
  461. - (void)openTaobao:(WKScriptMessage *)message {
  462. NSDictionary *dict = [self dictionaryWithJsonString:message.body];
  463. NSString *url = dict[@"taobaoUrl"];
  464. [self jumpToTaobaoWithUrl:url];
  465. }
  466. - (void)jumpToTaobaoWithUrl:(NSString *)url {
  467. id<AlibcTradePage> page = [AlibcTradePageFactory page:url];
  468. //淘客信息
  469. AlibcTradeTaokeParams *taoKeParams=[[AlibcTradeTaokeParams alloc] init];
  470. taoKeParams.pid= ALTK_PID;
  471. //打开方式
  472. AlibcTradeShowParams* showParam = [[AlibcTradeShowParams alloc] init];
  473. showParam.openType = AlibcOpenTypeNative;
  474. [[AlibcTradeSDK sharedInstance].tradeService openByUrl:url identity:@"trade" webView:nil parentController:self.parentViewController showParams:showParam taoKeParams:taoKeParams trackParam:nil tradeProcessSuccessCallback:^(AlibcTradeResult * _Nullable result) {
  475. } tradeProcessFailedCallback:^(NSError * _Nullable error) {
  476. }];
  477. }
  478. -(void)shareImageWithplatformType:(UMSocialPlatformType)platformType withDict:(NSDictionary *)dict{
  479. //创建分享消息对象
  480. UMSocialMessageObject *messageObject = [UMSocialMessageObject messageObject];
  481. //创建图片内容对象
  482. UMShareWebpageObject *shareObject = [UMShareWebpageObject shareObjectWithTitle:dict[@"shareTitle"] descr:dict[@"shareDescirpt"] thumImage:dict[@"shareImageUrl"]];
  483. shareObject.webpageUrl = dict[@"shareUrl"];
  484. messageObject.shareObject = shareObject;
  485. [[UMSocialManager defaultManager] shareToPlatform:platformType messageObject:messageObject currentViewController:nil completion:^(id data, NSError *error) {
  486. }];
  487. }
  488. /**
  489. kvo监听进度条
  490. @param keyPath keyPath description
  491. @param object object description
  492. @param change change description
  493. @param context context description
  494. */
  495. - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context{
  496. if ([keyPath isEqualToString:NSStringFromSelector(@selector(estimatedProgress))] && object == self.webView ) {
  497. [self.progressView setAlpha:1.0];
  498. [self.progressView setProgress:self.webView.estimatedProgress ];
  499. if (self.webView.estimatedProgress >= 1.0) {
  500. [UIView animateWithDuration:0.7 animations:^{
  501. [self.progressView setProgress:1.0 animated:YES];
  502. [self.progressView setAlpha:0.0];
  503. }];
  504. }
  505. }else{
  506. [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
  507. }
  508. }
  509. #pragma mark-
  510. #pragma mark- WKNavigationDelegate delegate
  511. /**
  512. 开始加载web的时候
  513. @param webView webView description
  514. @param navigation navigation description
  515. */
  516. - (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation{
  517. //开始加载的时候,让进度条显示
  518. self.progressView.hidden = NO;
  519. self.progressView.progress = 0;
  520. self.progressView.alpha = 1.0;
  521. [UIView animateWithDuration:0.8 animations:^{
  522. self.progressView.progress = 0.6;
  523. }];
  524. }
  525. /**
  526. 当网页加载完成的时候调用
  527. @param webView web描述
  528. @param navigation 导航的描述
  529. */
  530. - (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{
  531. if ([_redStr isEqualToString:@"红包"]) {
  532. [self.navigationBar setNavTitle:@"红包"];
  533. self.navigationBar.navTitleLabel.textColor = [UIColor whiteColor];
  534. }else{
  535. [self.navigationBar setNavTitle:self.webView.title];
  536. }
  537. [[UIApplication sharedApplication]setNetworkActivityIndicatorVisible:NO];
  538. [self updateNavigationBarButtons];
  539. [self.webView.scrollView.mj_header endRefreshing];
  540. }
  541. -(void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler
  542. {
  543. NSURL *url = navigationAction.request.URL;
  544. UIApplication *app = [UIApplication sharedApplication];
  545. // 打开appstore
  546. if ([url.absoluteString containsString:@"https://itunes.apple.com/cn/app/"])
  547. {
  548. if ([app canOpenURL:url])
  549. {
  550. //设备系统为IOS 10.0或者以上的
  551. if (@available(iOS 10.0, *)) {
  552. [[UIApplication sharedApplication] openURL:url options:@{} completionHandler:nil];
  553. } else {
  554. [[UIApplication sharedApplication] openURL:url];
  555. }
  556. decisionHandler(WKNavigationActionPolicyCancel);
  557. return;
  558. }
  559. }
  560. decisionHandler(WKNavigationActionPolicyAllow);
  561. }
  562. #pragma mark -----------
  563. - (void)updateNavigationBarButtons {
  564. if (self.webView.canGoBack) {
  565. [self.navigationBar setCustomLeftButtons:@[self.backButton,self.closeButton]];
  566. }else {
  567. [self.navigationBar setCustomLeftButtons:@[self.backButton]];
  568. }
  569. }
  570. - (void)backAction {
  571. NSArray *viewControllers = self.navigationController.viewControllers;
  572. if (viewControllers.count < 1){
  573. [self dismissViewControllerAnimated:YES completion:nil];
  574. }else {
  575. if (self.webView.canGoBack) {
  576. [self.webView goBack];
  577. }else{
  578. [self.navigationController popViewControllerAnimated:YES];
  579. }
  580. }
  581. }
  582. - (void)closeAction {
  583. [self.navigationController popViewControllerAnimated:YES];
  584. }
  585. -(void)redRuleClickAction
  586. {
  587. LDAdWebViewController *webV =[[LDAdWebViewController alloc]init];
  588. webV.url=redRulesUrl;
  589. [self.navigationController pushViewController:webV animated:YES];
  590. }
  591. - (void)refreshAction {
  592. [self.webView reload];
  593. }
  594. - (WKWebView *)webView{
  595. if (!_webView) {
  596. WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
  597. config.allowsInlineMediaPlayback = NO;
  598. _webView = [[WKWebView alloc]initWithFrame:CGRectMake(0, NavBarHeight, SCREEN_WIDTH, SCREEN_HEIGHT-NavBarHeight) configuration:config];
  599. if ([_redStr isEqualToString:@"红包"]) {
  600. _webView.frame=CGRectMake(0, NavBarHeight, SCREEN_WIDTH, SCREEN_HEIGHT-NavBarHeight-TabbarHeight);
  601. }
  602. _webView.backgroundColor = [UIColor colorWithRed:240.0/255 green:240.0/255 blue:240.0/255 alpha:1.0];
  603. _webView.navigationDelegate = self;
  604. _webView.UIDelegate = self;
  605. //使用kvo监听进度
  606. [_webView addObserver:self forKeyPath:NSStringFromSelector(@selector(estimatedProgress)) options:0 context:nil];
  607. //手势触摸滑动
  608. _webView.allowsBackForwardNavigationGestures = YES;
  609. //自适应
  610. [_webView sizeToFit];
  611. self.webView.scrollView.mj_header =[MJRefreshNormalHeader headerWithRefreshingBlock:^{
  612. [self refreshAction];
  613. }];
  614. }
  615. return _webView;
  616. }
  617. #pragma mark-
  618. #pragma mark- SetupConstraints
  619. /** 加载配置以及视图添加*/
  620. - (void)loadSubViewsConfiguration{
  621. [self.view addSubview:self.webView];
  622. }
  623. - (UIButton *)backButton {
  624. if (!_backButton) {
  625. _backButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 40, 40)];
  626. [_backButton setImage:[UIImage imageNamed:@"back"] forState:UIControlStateNormal];
  627. [_backButton addTarget:self action:@selector(backAction) forControlEvents:UIControlEventTouchUpInside];
  628. }
  629. return _backButton;
  630. }
  631. - (UIButton *)closeButton {
  632. if (!_closeButton) {
  633. _closeButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 40, 40)];
  634. [_closeButton setImage:[UIImage imageNamed:@"close_web"] forState:UIControlStateNormal];
  635. [_closeButton addTarget:self action:@selector(closeAction) forControlEvents:UIControlEventTouchUpInside];
  636. }
  637. return _closeButton;
  638. }
  639. - (UIButton *)refreshButton {
  640. if (!_refreshButton) {
  641. _refreshButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 40, 40)];
  642. [_refreshButton setImage:[UIImage imageNamed:@"icon_web_refresh"] forState:UIControlStateNormal];
  643. [_refreshButton addTarget:self action:@selector(refreshAction) forControlEvents:UIControlEventTouchUpInside];
  644. if ([_redStr isEqualToString:@"红包"]) {
  645. _refreshButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 90, 40)];
  646. [_refreshButton setImage:[UIImage imageNamed:@"Doubt"] forState:UIControlStateNormal];
  647. _refreshButton.titleLabel.font =[UIFont systemFontOfSize:13];
  648. [_refreshButton setTitle:@"关于红包" forState:UIControlStateNormal];
  649. [_refreshButton setButtonImageTitleStyle:ButtonImageTitleStyleRight padding:5];
  650. [_refreshButton addTarget:self action:@selector(redRuleClickAction) forControlEvents:UIControlEventTouchUpInside];
  651. }else{
  652. [self.refreshButton setImage:[UIImage imageNamed:@"icon_web_refresh"] forState:UIControlStateNormal];
  653. self.refreshButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 40, 40)];
  654. }
  655. }
  656. return _refreshButton;
  657. }
  658. - (UIProgressView *)progressView{
  659. if (!_progressView) {
  660. _progressView = [[UIProgressView alloc]initWithProgressViewStyle:UIProgressViewStyleDefault];
  661. _progressView.frame = CGRectMake(0, NavBarHeight, self.view.frame.size.width, 2);
  662. //设置进度条的色彩
  663. [_progressView setTrackTintColor:[UIColor colorWithRed:240.0/255 green:240.0/255 blue:240.0/255 alpha:1.0]];
  664. _progressView.progressTintColor = [UIColor homeRedColor];
  665. }
  666. return _progressView;
  667. }
  668. //观察的移除
  669. - (void)dealloc{
  670. [self.webView removeObserver:self forKeyPath:NSStringFromSelector(@selector(estimatedProgress))];
  671. [[NSNotificationCenter defaultCenter] removeObserver:self];
  672. }
  673. /**
  674. json字符串转字典
  675. */
  676. - (NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString
  677. {
  678. if (jsonString == nil) {
  679. return nil;
  680. }
  681. NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
  682. NSError *err;
  683. NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
  684. options:NSJSONReadingMutableContainers
  685. error:&err];
  686. if(err)
  687. {
  688. NSLog(@"json解析失败:%@",err);
  689. return nil;
  690. }
  691. return dic;
  692. }
  693. /**
  694. 字典转json字符串
  695. */
  696. - (NSString *)convertToJsonData:(NSDictionary *)dict
  697. {
  698. NSError *error;
  699. NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];
  700. NSString *jsonString;
  701. if (!jsonData) {
  702. NSLog(@"%@",error);
  703. }else{
  704. jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
  705. }
  706. NSMutableString *mutStr = [NSMutableString stringWithString:jsonString];
  707. NSRange range = {0,jsonString.length};
  708. //去掉字符串中的空格
  709. [mutStr replaceOccurrencesOfString:@" " withString:@"" options:NSLiteralSearch range:range];
  710. NSRange range2 = {0,mutStr.length};
  711. //去掉字符串中的换行符
  712. [mutStr replaceOccurrencesOfString:@"\n" withString:@"" options:NSLiteralSearch range:range2];
  713. return mutStr;
  714. }
  715. - (void)didReceiveMemoryWarning {
  716. [super didReceiveMemoryWarning];
  717. // Dispose of any resources that can be recreated.
  718. }
  719. /*
  720. #pragma mark - Navigation
  721. // In a storyboard-based application, you will often want to do a little preparation before navigation
  722. - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
  723. // Get the new view controller using [segue destinationViewController].
  724. // Pass the selected object to the new view controller.
  725. }
  726. */
  727. @end