ZCBaseWebView.m 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766
  1. //
  2. // ZCBaseBaseWebView.m
  3. // HuaKaiChat
  4. //
  5. // Created by 张灿 on 2017/6/28.
  6. // Copyright © 2017年 huakai. All rights reserved.
  7. //
  8. #import "ZCBaseWebView.h"
  9. #import <WebKit/WebKit.h>
  10. #import "YOUPAILZUserShowVC.h"
  11. #import "YOUPAILZLiveAudienceVC.h"
  12. #import "UIViewController+TFPresent.h"
  13. //#import "IPAManager.h"
  14. //#import "WXApi.h"
  15. #import "YOUPAILCIMSessionVC.h"
  16. #import "YOUPAILCShareModel.h"
  17. #import <UMShare/UMShare.h>
  18. #import "YOUPAILZShareApplicationWindow.h"
  19. #import "IPAManager.h"
  20. #import "YOUPAIHRWebWindow.h"
  21. @interface ZCBaseWebView()<WKUIDelegate,WKNavigationDelegate,ZCBaseWebProgressViewDelegate,WKScriptMessageHandler>
  22. @property (nonatomic,assign) double estimatedProgress;
  23. @property (nonatomic,strong) NSURLRequest *originRequest;
  24. @property (nonatomic,strong) NSURLRequest *currentRequest;
  25. @property (nonatomic,strong) UILabel *tipLabel;
  26. @property (nonatomic,strong) UILabel *errorLabel;
  27. @property (nonatomic,strong) ZCBaseWebProgressView* ZCBaseWebProgressView;
  28. @property (nonatomic,assign)BOOL ResetFlag;//已设置标志
  29. @property (nonatomic,strong) WKWebView* wkwebView;
  30. @end
  31. @implementation ZCBaseWebView
  32. @synthesize realWebView = _realWebView;
  33. - (UILabel *)errorLabel{
  34. if (!_errorLabel) {
  35. _errorLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 10, KScreenWidth, 30)];
  36. _errorLabel.text = @"网页加载失败";
  37. _errorLabel.textColor = DecColorFromRGB(110, 115, 116);
  38. _errorLabel.font = [UIFont systemFontOfSize:15];
  39. _errorLabel.textAlignment = NSTextAlignmentCenter;
  40. [self addSubview:_errorLabel];
  41. }
  42. return _errorLabel;
  43. }
  44. - (UILabel *)tipLabel{
  45. if (!_tipLabel) {
  46. _tipLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 10, KScreenWidth, 30)];
  47. NSString *endStr;
  48. NSRange start = [self.contentUrl rangeOfString:@"//"];
  49. NSString* startStr = [self.contentUrl substringFromIndex:start.location+2];
  50. NSRange end = [startStr rangeOfString:@"/"];
  51. if (end.length==0) {
  52. endStr = startStr;
  53. }else{
  54. endStr = [startStr substringToIndex:end.location];
  55. }
  56. _tipLabel.text = [NSString stringWithFormat:@"网页由 %@ 提供",endStr];
  57. _tipLabel.textColor = DecColorFromRGB(110, 115, 116);
  58. _tipLabel.font = [UIFont systemFontOfSize:15];
  59. _tipLabel.textAlignment = NSTextAlignmentCenter;
  60. [self.wkwebView addSubview:_tipLabel];
  61. }
  62. return _tipLabel;
  63. }
  64. - (instancetype)init
  65. {
  66. return [self initWithFrame:CGRectMake(0, 0, KScreenWidth, KScreenHeight-NavBarHeight)];
  67. }
  68. - (instancetype)initWithFrame:(CGRect)frame
  69. {
  70. self = [super initWithFrame:frame];
  71. if (self)
  72. {
  73. [self _initMyself];
  74. }
  75. return self;
  76. }
  77. - (instancetype)initWithCoder:(NSCoder *)coder
  78. {
  79. self = [super initWithCoder:coder];
  80. if (self) {
  81. [self _initMyself];
  82. }
  83. return self;
  84. }
  85. -(void)_initMyself
  86. {
  87. // self.backgroundColor = DecColorFromRGB(46, 49, 50);
  88. self.wkwebView.scrollView.bounces = NO;
  89. self.backgroundColor = LCBkgColor;
  90. self.ResetFlag = NO;
  91. Class wkWebView = NSClassFromString(@"WKWebView");
  92. if(wkWebView)
  93. {
  94. [self initWKWebView];
  95. }
  96. else
  97. {
  98. }
  99. // self.scalesPageToFit = YES;
  100. [self.realWebView setFrame:self.bounds];
  101. [self.realWebView setAutoresizingMask:UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight];
  102. [self addSubview:self.realWebView];
  103. }
  104. -(void)initWKWebView
  105. {
  106. WKUserContentController *userContentController = [[WKUserContentController alloc] init];
  107. [userContentController addScriptMessageHandler:self name:@"openUserDetail"];//js调用跳转至用户详情
  108. [userContentController addScriptMessageHandler:self name:@"openUserLive"];// js调用跳转至直播间
  109. [userContentController addScriptMessageHandler:self name:@"openActivity"]; //js调用可跳转app指定内页
  110. [userContentController addScriptMessageHandler:self name:@"showPay"]; // 支付
  111. // [userContentController addScriptMessageHandler:self name:@"showShareDialog"];// 分享
  112. [userContentController addScriptMessageHandler:self name:@"copyInviteCode"];// 复制到剪切板
  113. [userContentController addScriptMessageHandler:self name:@"showPosterDialog"];// 分享推广
  114. [userContentController addScriptMessageHandler:self name:@"getUserId"];// 把用户id传给H5
  115. [userContentController addScriptMessageHandler:self name:@"startP2PSession"];// 客服
  116. [userContentController addScriptMessageHandler:self name:@"showH5Dialog"]; //js调用Web窗口
  117. [userContentController addScriptMessageHandler:self name:@"closeWindow"]; //关闭界面
  118. [userContentController addScriptMessageHandler:self name:@"showNewShareDialog"]; //第三方分享
  119. [userContentController addScriptMessageHandler:self name:@"openMainActivity"]; //js调用可跳转app指定内页
  120. WKWebViewConfiguration* configuration = [[NSClassFromString(@"WKWebViewConfiguration") alloc] init];
  121. configuration.preferences = [NSClassFromString(@"WKPreferences") new];
  122. configuration.userContentController = userContentController;
  123. WKWebView* webView = [[NSClassFromString(@"WKWebView") alloc] initWithFrame:self.bounds configuration:configuration];
  124. webView.UIDelegate = self;
  125. webView.navigationDelegate = self;
  126. webView.backgroundColor = [UIColor clearColor];
  127. webView.opaque = YES;
  128. webView.allowsLinkPreview = NO;
  129. webView.allowsBackForwardNavigationGestures = YES;
  130. [webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
  131. [webView addObserver:self forKeyPath:@"title" options:NSKeyValueObservingOptionNew context:nil];
  132. self.wkwebView = webView;
  133. _realWebView = webView;
  134. [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(youpaifApplePaySuccess:) name:@"yqApplePaySuccess" object:nil];
  135. }
  136. - (void)youpaifApplePaySuccess:(NSNotification*)noti{
  137. [self.wkwebView evaluateJavaScript:@"callback()" completionHandler:^(id _Nullable result, NSError * _Nullable error) {
  138. NSLog(@"%@", error);
  139. }];
  140. [self.wkwebView evaluateJavaScript:@"vue_onload()" completionHandler:^(id _Nullable result, NSError * _Nullable error) {
  141. NSLog(@"%@", error);
  142. }];
  143. }
  144. //js调oc
  145. - (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message{
  146. if ([message.name isEqualToString:@"openUserDetail"]) {
  147. //int userId,int type // 用户id
  148. NSLog(@"方法名:%@", message.name);
  149. NSLog(@"参数:%@", message.body);
  150. if ([message.body isKindOfClass:[NSDictionary class]]) {
  151. NSDictionary *dict = message.body;
  152. NSNumber *type = dict[@"type"];
  153. NSNumber *userId = dict[@"userId"];
  154. if ([type isEqualToNumber:@1]) {
  155. // YOUPAILZUserShowVC *vc = [YOUPAILZUserShowVC new];
  156. // vc.youpaipuserId = [NSString stringWithFormat:@"%@",userId];
  157. // [self.nav pushViewController:vc animated:YES];
  158. YMPersonalPageViewModel *personalPageVM = [[YMPersonalPageViewModel alloc]initWithParams:@{
  159. ParamsId:@([userId intValue])
  160. }];
  161. [YMRouter openURL:stringFormat(@"%@%@", YM_ROUTER_URL_PREFIX, YM_ROUTER_PERSONAL_PAGE) withUserInfo:@{
  162. RouterViewModel:personalPageVM
  163. } completion:nil];
  164. }
  165. }
  166. }else if ([message.name isEqualToString:@"openUserLive"]){
  167. // String roomId // 直播间id
  168. NSLog(@"直播方法名:%@", message.name);
  169. NSLog(@"直播参数:%@", message.body);
  170. NSNumber *roomId = message.body;
  171. [ZCHUDHelper showWithStatus:nil];
  172. WeakSelf;
  173. [LCHttpHelper requestWithURLString:JoinLive parameters:@{@"room_id":[NSString stringWithFormat:@"%@",roomId]} needToken:YES type:HttpRequestTypePost success:^(id responseObject) {
  174. NSDictionary* dict = (NSDictionary*)responseObject;
  175. NSInteger code = [[dict objectForKey:@"code"] integerValue];
  176. if (code == 0) {
  177. [ZCHUDHelper dismiss];
  178. [[YOUPAILZChatRoomManager shareManager] youpaifcloseChatRoom];
  179. YOUPAILZLiveModel *liveModel = [YOUPAILZLiveModel mj_objectWithKeyValues:[dict objectForKey:@"data"]];
  180. YOUPAILZLiveAudienceVC *audienceVC = [[YOUPAILZLiveAudienceVC alloc] initWithModel:liveModel];
  181. [weakSelf.nav pushViewController:audienceVC animated:YES];
  182. }else{
  183. [ZCHUDHelper showTitle:[dict objectForKey:@"message"]];
  184. }
  185. } failure:^(NSError *error) {
  186. [ZCHUDHelper showTitle:error.localizedDescription];
  187. }];
  188. }else if ([message.name isEqualToString:@"openActivity"]){
  189. //int linkType,String linkUrl
  190. // NSLog(@"openActivity方法名:%@", message.name);
  191. // NSLog(@"openActivity参数:%@", message.body);
  192. if ([message.body isKindOfClass:[NSDictionary class]]) {
  193. NSDictionary *dict = message.body;
  194. NSNumber *link_type = dict[@"linkType"];
  195. NSString *link_url = dict[@"linkUrl"];
  196. if ([link_type isEqualToNumber:@1]) {
  197. ZCBaseWebVC* baseWeb = [[ZCBaseWebVC alloc]init];
  198. baseWeb.contentUrl = link_url;
  199. [self.nav pushViewController:baseWeb animated:YES];
  200. }else if ([link_type isEqualToNumber:@2]||[link_type isEqualToNumber:@3]){
  201. [[LCTools getCurrentVC] youpaifpageToStr:link_url];
  202. }
  203. }
  204. }else if ([message.name isEqualToString:@"openMainActivity"]){
  205. if ([message.body isKindOfClass:[NSDictionary class]]) {
  206. NSDictionary *dict = message.body;
  207. NSString *type = dict[@"type"];
  208. [[LCTools getCurrentVC] youpaifpageToStr:type];
  209. }
  210. }else if ([message.name isEqualToString:@"showPay"]){
  211. if ([message.body isKindOfClass:[NSDictionary class]]) {
  212. NSDictionary *dict = message.body;
  213. NSString *ios_product_id = [NSString stringWithFormat:@"%@",dict[@"ios_product_id"]];
  214. [self applePay:ios_product_id];
  215. }
  216. }
  217. // else if([message.name isEqualToString:@"showShareDialog"]){
  218. // if ([message.body isKindOfClass:[NSDictionary class]]) {
  219. // NSDictionary *dict = message.body;
  220. // NSString *imageUrl = [NSString stringWithFormat:@"%@",dict[@"imageUrl"]];
  221. // NSString *weChatUrl = [NSString stringWithFormat:@"%@",dict[@"weChatUrl"]];
  222. // [self shareWithQrcodeUrl:imageUrl Url:weChatUrl];
  223. // }
  224. //
  225. // }
  226. else if([message.name isEqualToString:@"copyInviteCode"]){
  227. if ([message.body isKindOfClass:[NSDictionary class]]) {
  228. NSDictionary *dict = message.body;
  229. NSString *inviteCode = [NSString stringWithFormat:@"%@",dict[@"inviteCode"]];
  230. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  231. pasteboard.string = inviteCode;
  232. [ZCHUDHelper showTitle:@"复制成功,快去粘贴吧!"];
  233. }
  234. }else if([message.name isEqualToString:@"showPosterDialog"]){
  235. if ([message.body isKindOfClass:[NSDictionary class]]) {
  236. NSDictionary *dict = message.body;
  237. YOUPAILZShareApplicationModel *model = [YOUPAILZShareApplicationModel mj_objectWithKeyValues:dict];
  238. YOUPAILZShareApplicationWindow *vc = [[YOUPAILZShareApplicationWindow alloc] init];
  239. vc.youpaipmodel = model;
  240. vc.isTouchDismiss = YES;
  241. [[LCTools getCurrentVC] TFPresentVC:vc completion:^{}];
  242. }
  243. }else if([message.name isEqualToString:@"getUserId"]){
  244. if ([message.body isKindOfClass:[NSDictionary class]]) {
  245. NSDictionary *dict = message.body;
  246. NSString *methodName = [dict objectForKey:@"fn"];
  247. [self.wkwebView evaluateJavaScript:[NSString stringWithFormat:@"%@('%@')",methodName,[LCSaveModel getUserModel].youpaipuserinfo.youpaipuser_id] completionHandler:^(id _Nullable result, NSError * _Nullable error) {
  248. NSLog(@"%@", error);
  249. }];
  250. }
  251. }else if([message.name isEqualToString:@"startP2PSession"]){
  252. NIMSession *session = [NIMSession session:[LCSaveData getServerId] type:NIMSessionTypeP2P];
  253. if (session) {
  254. @weakify(self);
  255. [ZCHUDHelper show];
  256. [[[NIMSDK sharedSDK] userManager] fetchUserInfos:@[session.sessionId] completion:^(NSArray<NIMUser *> * _Nullable users, NSError * _Nullable error) {
  257. @strongify(self);
  258. [ZCHUDHelper dismiss];
  259. YOUPAILCIMSessionVC *vc = [[YOUPAILCIMSessionVC alloc] initWithSession:session];
  260. [[LCTools getContainNavigationControllerCurrentVC].navigationController pushViewController:vc animated:YES];
  261. }];
  262. }
  263. }else if ([message.name isEqualToString:@"showH5Dialog"]){
  264. //int linkType,String linkUrl
  265. // NSLog(@"openActivity方法名:%@", message.name);
  266. // NSLog(@"openActivity参数:%@", message.body);
  267. if ([message.body isKindOfClass:[NSDictionary class]]) {
  268. NSDictionary *dict = message.body;
  269. NSString *gravity = dict[@"gravity"];
  270. CGFloat width = [dict[@"width"] floatValue];
  271. CGFloat height = [dict[@"height"] floatValue];
  272. NSString *loadUrl = dict[@"loadUrl"];
  273. YOUPAIHRWebWindow *window = [[YOUPAIHRWebWindow alloc] init];
  274. window.youpaipgravity = gravity;
  275. window.youpaipwidth = width;
  276. window.youpaipheight = height;
  277. window.youpaipurl = loadUrl;
  278. [[LCTools getCurrentVC] TFPresentVC:window completion:^{}];
  279. }
  280. }else if ([message.name isEqualToString:@"closeWindow"]){
  281. [[LCTools getContainNavigationControllerCurrentVC].navigationController popViewControllerAnimated:YES];
  282. }else if([message.name isEqualToString:@"showNewShareDialog"]){
  283. if ([message.body isKindOfClass:[NSDictionary class]]) {
  284. NSDictionary *dict = message.body;
  285. NSString *title = [NSString stringWithFormat:@"%@",dict[@"title"]];
  286. NSString *linkUrl = [NSString stringWithFormat:@"%@",dict[@"linkUrl"]];
  287. NSString *thumbUrl = [NSString stringWithFormat:@"%@",dict[@"thumbUrl"]];
  288. NSString *des = [NSString stringWithFormat:@"%@",dict[@"des"]];
  289. [self shareWithTitle:title linkUrl:linkUrl thumbUrl:thumbUrl des:des];
  290. }
  291. }
  292. }
  293. - (void)shareWithTitle:(NSString *)title linkUrl:(NSString *)linkUrl thumbUrl:(NSString *)thumbUrl des:(NSString *)des{
  294. ZCShareActionBtn *action1 = [ZCShareActionBtn actionWithTitle:@"微信" image:[UIImage imageNamed:@"vqu_images_share_weixin"] andblock:^(NSString *str) {
  295. [self shareWithPlatform:UMSocialPlatformType_WechatSession title:title linkUrl:linkUrl thumbUrl:thumbUrl des:des];
  296. }];
  297. ZCShareActionBtn *action2 = [ZCShareActionBtn actionWithTitle:@"朋友圈" image:[UIImage imageNamed:@"vqu_images_share_weixin_timeline"] andblock:^(NSString *str) {
  298. [self shareWithPlatform:UMSocialPlatformType_WechatTimeLine title:title linkUrl:linkUrl thumbUrl:thumbUrl des:des];
  299. }];
  300. // ZCShareActionBtn *action3 = [ZCShareActionBtn actionWithTitle:@"微博" image:[UIImage imageNamed:@"vqu_images_share_weibo"] andblock:^(NSString *str) {
  301. // UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  302. // pasteboard.string = linkUrl;
  303. // [ZCHUDHelper showTitle:@"复制成功,快去粘贴吧!"];
  304. // }];
  305. ZCShareActionBtn *action4 = [ZCShareActionBtn actionWithTitle:@"QQ" image:[UIImage imageNamed:@"vqu_images_share_qq"] andblock:^(NSString *str) {
  306. [self shareWithPlatform:UMSocialPlatformType_QQ title:title linkUrl:linkUrl thumbUrl:thumbUrl des:des];
  307. }];
  308. ZCShareActionBtn *action5 = [ZCShareActionBtn actionWithTitle:@"QQ空间" image:[UIImage imageNamed:@"vqu_images_share_qzone"] andblock:^(NSString *str) {
  309. [self shareWithPlatform:UMSocialPlatformType_Qzone title:title linkUrl:linkUrl thumbUrl:thumbUrl des:des];
  310. }];
  311. @weakify(self);
  312. ZCShareActionBtn *action6 = [ZCShareActionBtn actionWithTitle:@"生成图片" image:[UIImage imageNamed:@"vqu_images_share_qrcode"] andblock:^(NSString *str) {
  313. @strongify(self);
  314. [self.wkwebView evaluateJavaScript:@"notifyPoster()" completionHandler:^(id _Nullable result, NSError * _Nullable error) {
  315. NSLog(@"%@", error);
  316. }];
  317. // YOUPAILCMyQRCodeVC* qrcodeVC = [[YOUPAILCMyQRCodeVC alloc]init];
  318. // qrcodeVC.qrcode = qrcodeUrl;
  319. // qrcodeVC.url = url;
  320. // [[LCTools getCurrentVC].navigationController pushViewController:qrcodeVC animated:YES];
  321. // YOUPAILZShareApplicationWindow *vc = [[YOUPAILZShareApplicationWindow alloc] init];
  322. // vc.isTouchDismiss = YES;
  323. // [[LCTools getCurrentVC] TFPresentVC:vc completion:^{}];
  324. }];
  325. ZCShareActionBtn *action7 = [ZCShareActionBtn actionWithTitle:@"复制链接" image:[UIImage imageNamed:@"vqu_images_share_link"] andblock:^(NSString *str) {
  326. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  327. pasteboard.string = linkUrl;
  328. [ZCHUDHelper showTitle:@"复制成功,快去粘贴吧!"];
  329. }];
  330. ZCShareSheetView* shareView = [[ZCShareSheetView alloc]initWithTitle:@"推荐给好友" andShowCancelButton:YES andAction:@[action6,action1,action2,action4,action5,action7] column:5];
  331. shareView.alertWindow.hidden = NO;
  332. [shareView show];
  333. // [LCHttpHelper requestWithURLString:InviteInit parameters:nil needToken:YES type:(HttpRequestTypePost) success:^(id responseObject) {
  334. // NSDictionary* dict = (NSDictionary*)responseObject;
  335. // NSInteger code = [[dict objectForKey:@"code"] integerValue];
  336. // if (code==0) {//成功
  337. // YOUPAILCShareModel *shareModel = [YOUPAILCShareModel mj_objectWithKeyValues:[[dict objectForKey:@"data"]objectForKey:@"share"]];
  338. // NSString *qrcode = [[dict objectForKey:@"data"]objectForKey:@"qrcode"];
  339. // NSString *url = shareModel.url;
  340. //
  341. // }
  342. // } failure:^(NSError *error) {
  343. //
  344. // }];
  345. }
  346. - (void)shareWithPlatform:(UMSocialPlatformType)platformType title:(NSString *)title linkUrl:(NSString *)linkUrl thumbUrl:(NSString *)thumbUrl des:(NSString *)des{
  347. UMSocialMessageObject* message = [[UMSocialMessageObject alloc]init];
  348. NSData* imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:thumbUrl]];
  349. UMShareWebpageObject* webPage = [UMShareWebpageObject shareObjectWithTitle:title descr:des thumImage:imageData];
  350. webPage.webpageUrl = linkUrl;
  351. message.shareObject = webPage;
  352. @weakify(self);
  353. [[UMSocialManager defaultManager] shareToPlatform:platformType messageObject:message currentViewController:nil completion:^(id result, NSError *error) {
  354. if (error == nil) {
  355. [LCHttpHelper requestWithURLString:ShareTask parameters:@{} needToken:YES type:(HttpRequestTypePost) success:^(id responseObject) {
  356. NSDictionary* dict = (NSDictionary*)responseObject;
  357. NSInteger code = [[dict objectForKey:@"code"] integerValue];
  358. if (code==0) {//成功
  359. @strongify(self);
  360. [self youpaifApplePaySuccess:nil];
  361. }
  362. } failure:^(NSError *error) {
  363. }];
  364. }
  365. }];
  366. }
  367. - (void)applePay:(NSString *)ios_product_id{
  368. // self.buyBtn.userInteractionEnabled = NO;
  369. /// 内购
  370. [ZCHUDHelper showWithStatus:@"支付中..."];
  371. NSLog(@"%@",ios_product_id);
  372. [[IPAManager shareIAPManager] startPurchWithID:ios_product_id completeHandle:^(IAPPurchType type, NSString *data) {
  373. NSLog(@"type = %ld",type);
  374. if (type == IAPPurchSuccess) {
  375. [LCSaveData saveReceiptData:data];
  376. [self requestApplePayBack:data];
  377. }else{
  378. // dispatch_async(dispatch_get_main_queue(), ^{
  379. // self.buyBtn.userInteractionEnabled = YES;
  380. // });
  381. NSString *title = @"";
  382. switch (type) {
  383. case IAPPurchFailed:
  384. title = @"购买失败";
  385. break;
  386. case IAPPurchCancle:
  387. title = @"已取消购买";
  388. break;
  389. case IAPPurchVerFailed:
  390. title = @"订单校验失败";
  391. break;
  392. // case IAPPurchVerSuccess:
  393. // NSLog(@"订单校验成功");
  394. // break;
  395. case IAPPurchNotArrow:
  396. title = @"不允许程序内付费";
  397. break;
  398. default:
  399. break;
  400. }
  401. if (title.length == 0) {
  402. [ZCHUDHelper dismiss];
  403. }else{
  404. [ZCHUDHelper showTitle:title];
  405. }
  406. }
  407. }];
  408. }
  409. - (void)requestApplePayBack:(NSString *)receipt_data{
  410. [LCHttpHelper requestWithURLString:ApplePayBack parameters:@{@"receipt_data":receipt_data} needToken:YES type:(HttpRequestTypePost) success:^(id responseObject) {
  411. NSDictionary* dict = (NSDictionary*)responseObject;
  412. NSInteger code = [[dict objectForKey:@"code"] integerValue];
  413. // dispatch_async(dispatch_get_main_queue(), ^{
  414. // self.buyBtn.userInteractionEnabled = YES;
  415. // });
  416. if (code == 0) {
  417. [LCSaveData removeReceiptData:receipt_data];
  418. NSInteger type = 4;
  419. // if (![LCSaveData getOnlineVersion]) {
  420. // type = 4;
  421. // }
  422. // [self initDataWithType:type];
  423. // if (self.paySuccessBlock != nil) {
  424. // self.paySuccessBlock();
  425. // }
  426. [self.wkwebView evaluateJavaScript:@"callback()" completionHandler:^(id _Nullable result, NSError * _Nullable error) {
  427. NSLog(@"%@", error);
  428. }];
  429. }
  430. [ZCHUDHelper showTitle:[dict objectForKey:@"message"]];
  431. } failure:^(NSError *error) {
  432. // dispatch_async(dispatch_get_main_queue(), ^{
  433. // self.buyBtn.userInteractionEnabled = YES;
  434. // });
  435. [ZCHUDHelper showTitle:error.localizedDescription];
  436. }];
  437. }
  438. -(void)loadRequest:(NSURLRequest *)request
  439. {
  440. [(WKWebView*)self.realWebView loadRequest:request];
  441. }
  442. - (void)loadHTMLString:(NSString *)string baseURL:(nullable NSURL *)baseURL
  443. {
  444. [(WKWebView*)self.realWebView loadHTMLString:string baseURL:baseURL];
  445. }
  446. //计算js代码
  447. - (nullable NSString *)stringByEvaluatingJavaScriptFromString:(NSString * _Nullable)script
  448. {
  449. //如果是用wkwebview 来获取title 可以直接使用title属性
  450. if ([script isEqualToString:@"document.title"]) {
  451. return ((WKWebView*)self.realWebView).title;
  452. }else{
  453. __block NSString *resultString = nil;
  454. [(WKWebView*)self.realWebView evaluateJavaScript:script completionHandler:^(id result, NSError *error) {
  455. if (error == nil) {
  456. if (result != nil) {
  457. resultString = [NSString stringWithFormat:@"%@", result];
  458. }
  459. } else {
  460. NSLog(@"evaluateJavaScript error : %@", error.localizedDescription);
  461. }
  462. }];
  463. while (resultString == nil)
  464. {
  465. [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
  466. }
  467. return resultString;
  468. }
  469. }
  470. #pragma mark --> WKWebView的代理方法
  471. -(void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler
  472. {
  473. BOOL resultBOOL = YES;
  474. BOOL isLoadingDisableScheme = [self isLoadingWKWebViewDisableScheme:navigationAction.request.URL];
  475. if(resultBOOL && !isLoadingDisableScheme)
  476. {
  477. self.currentRequest = navigationAction.request;
  478. if(navigationAction.targetFrame == nil)
  479. {
  480. [webView loadRequest:navigationAction.request];
  481. }
  482. decisionHandler(WKNavigationActionPolicyAllow);
  483. }
  484. else
  485. {
  486. decisionHandler(WKNavigationActionPolicyCancel);
  487. }
  488. }
  489. -(void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation
  490. {
  491. }
  492. -(void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation
  493. {
  494. [self callback_webViewDidFinishLoad];
  495. }
  496. - (void)webView:(WKWebView *) webView didFailProvisionalNavigation: (WKNavigation *) navigation withError: (NSError *) error
  497. {
  498. [self callback_webViewDidFailLoadWithError:error];
  499. }
  500. - (void)webView: (WKWebView *)webView didFailNavigation:(WKNavigation *) navigation withError: (NSError *) error
  501. {
  502. [self callback_webViewDidFailLoadWithError:error];
  503. }
  504. #pragma mark- CALLBACK IMYVKWebView Delegate
  505. - (void)callback_webViewDidFinishLoad
  506. {
  507. if([self.delegate respondsToSelector:@selector(webViewDidFinishLoad:)])
  508. {
  509. [self.delegate webViewDidFinishLoad:self];
  510. }
  511. if (!self.ResetFlag) {
  512. self.scrollView.backgroundColor = [UIColor clearColor];
  513. [self.wkwebView insertSubview:self.tipLabel belowSubview:self.wkwebView.scrollView];
  514. self.ResetFlag = YES;
  515. }
  516. }
  517. - (void)callback_webViewDidFailLoadWithError:(NSError *)error
  518. {
  519. if([self.delegate respondsToSelector:@selector(webView:didFailLoadWithError:)])
  520. {
  521. [self.delegate webView:self didFailLoadWithError:error];
  522. }
  523. [self insertSubview:self.errorLabel belowSubview:self.realWebView];
  524. }
  525. -(BOOL)callback_webViewShouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(NSInteger)navigationType
  526. {
  527. BOOL resultBOOL = YES;
  528. if([self.delegate respondsToSelector:@selector(webView:shouldStartLoadWithRequest:navigationType:)])
  529. {
  530. if(navigationType == -1) {
  531. navigationType = 5;
  532. }
  533. resultBOOL = YES;
  534. }
  535. return resultBOOL;
  536. }
  537. -(UIScrollView *)scrollView
  538. {
  539. return [(id)self.realWebView scrollView];
  540. }
  541. #pragma mark- 基础方法
  542. #pragma mark- 如果没有找到方法 去realWebView 中调用
  543. -(BOOL)respondsToSelector:(SEL)aSelector
  544. {
  545. BOOL hasResponds = [super respondsToSelector:aSelector];
  546. if(hasResponds == NO)
  547. {
  548. hasResponds = [self.delegate respondsToSelector:aSelector];
  549. }
  550. if(hasResponds == NO)
  551. {
  552. hasResponds = [self.realWebView respondsToSelector:aSelector];
  553. }
  554. return hasResponds;
  555. }
  556. ///判断当前加载的url是否是WKWebView不能打开的协议类型
  557. - (BOOL)isLoadingWKWebViewDisableScheme:(NSURL *)url
  558. {
  559. BOOL retValue = NO;
  560. //判断是否正在加载WKWebview不能识别的协议类型:phone numbers, email address, maps, etc.
  561. if([url.scheme isEqualToString:@"tel"]) {
  562. UIApplication *app = [UIApplication sharedApplication];
  563. if ([app canOpenURL:url]) {
  564. [app openURL:url];
  565. retValue = YES;
  566. }
  567. }
  568. return retValue;
  569. }
  570. //WkWebView的progress 回调
  571. -(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
  572. {
  573. if([keyPath isEqualToString:@"estimatedProgress"])
  574. {
  575. self.estimatedProgress = [change[NSKeyValueChangeNewKey] doubleValue];
  576. [self callback_webViewUpdateProgress:self.estimatedProgress];
  577. }
  578. else if([keyPath isEqualToString:@"title"])
  579. {
  580. self.title = change[NSKeyValueChangeNewKey];
  581. if([self.delegate respondsToSelector:@selector(webViewDidFinishLoad:)])
  582. {
  583. [self.delegate webViewDidFinishLoad:self];
  584. }
  585. }
  586. }
  587. //uiwebview的progress njk progress的代理方法
  588. -(void)webViewProgress:(ZCBaseWebProgressView *)webViewProgress updateProgress:(float)progress
  589. {
  590. self.estimatedProgress = progress;
  591. [self callback_webViewUpdateProgress:progress];
  592. }
  593. - (void)callback_webViewUpdateProgress:(float)progress
  594. {
  595. if([self.delegate respondsToSelector:@selector(webView:updateProgress:)])
  596. {
  597. [self.delegate webView:self updateProgress:progress];
  598. }
  599. }
  600. #pragma mark- 清理
  601. -(void)dealloc
  602. {
  603. WKWebView* webView = _realWebView;
  604. webView.UIDelegate = nil;
  605. webView.navigationDelegate = nil;
  606. [webView removeObserver:self forKeyPath:@"estimatedProgress"];
  607. [webView removeObserver:self forKeyPath:@"title"];
  608. [_realWebView scrollView].delegate = nil;
  609. [_realWebView stopLoading];
  610. [_realWebView removeFromSuperview];
  611. _realWebView = nil;
  612. [[NSNotificationCenter defaultCenter] removeObserver:self];
  613. }
  614. @end
  615. #pragma mark - ZCBaseWebProgressView
  616. NSString *completeRPCURLPath = @"/ZCBaseWebProgressViewproxy/complete";
  617. const float NJKInitialProgressValue = 0.1f;
  618. const float NJKInteractiveProgressValue = 0.5f;
  619. const float NJKFinalProgressValue = 0.9f;
  620. @implementation ZCBaseWebProgressView
  621. {
  622. NSUInteger _loadingCount;
  623. NSUInteger _maxLoadCount;
  624. NSURL *_currentURL;
  625. BOOL _interactive;
  626. }
  627. - (id)init
  628. {
  629. self = [super init];
  630. if (self) {
  631. _maxLoadCount = _loadingCount = 0;
  632. _interactive = NO;
  633. }
  634. return self;
  635. }
  636. - (void)startProgress
  637. {
  638. if (_progress < NJKInitialProgressValue) {
  639. [self setProgress:NJKInitialProgressValue];
  640. }
  641. }
  642. - (void)incrementProgress
  643. {
  644. float progress = self.progress;
  645. float maxProgress = _interactive ? NJKFinalProgressValue : NJKInteractiveProgressValue;
  646. float remainPercent = (float)_loadingCount / (float)_maxLoadCount;
  647. float increment = (maxProgress - progress) * remainPercent;
  648. progress += increment;
  649. progress = fmin(progress, maxProgress);
  650. [self setProgress:progress];
  651. }
  652. - (void)completeProgress
  653. {
  654. [self setProgress:1.0];
  655. }
  656. - (void)setProgress:(float)progress
  657. {
  658. // progress should be incremental only
  659. if (progress > _progress || progress == 0) {
  660. _progress = progress;
  661. if ([_progressDelegate respondsToSelector:@selector(webViewProgress:updateProgress:)]) {
  662. [_progressDelegate webViewProgress:self updateProgress:progress];
  663. }
  664. if (_progressBlock) {
  665. _progressBlock(progress);
  666. }
  667. }
  668. }
  669. - (void)reset
  670. {
  671. _maxLoadCount = _loadingCount = 0;
  672. _interactive = NO;
  673. [self setProgress:0.0];
  674. }
  675. @end