Commit 6167454c cgx

解决wkwebview cookie不同步巨坑

1 个父辈 f44682f1
...@@ -8,11 +8,10 @@ ...@@ -8,11 +8,10 @@
#import "AISleepCoachController.h" #import "AISleepCoachController.h"
#import <WebKit/WebKit.h> #import <WebKit/WebKit.h>
#import <JavaScriptCore/JavaScriptCore.h> #import <JavaScriptCore/JavaScriptCore.h>
#import "WKWebView+Extras.h"
@interface AISleepCoachController () <WKNavigationDelegate, WKScriptMessageHandler, WKUIDelegate> @interface AISleepCoachController () <WKNavigationDelegate, WKScriptMessageHandler, WKUIDelegate>
@property (strong, nonatomic) WKWebView *aiWebView; @property (strong, nonatomic) WKWebView *aiWebView;
@property (strong, nonatomic) NSURLRequest *request; @property (strong, nonatomic) NSMutableURLRequest *request;
@property (strong, nonatomic) UIProgressView *progressView; @property (strong, nonatomic) UIProgressView *progressView;
@property (nonatomic, strong) ExceptionDefaultView *exceptionView; @property (nonatomic, strong) ExceptionDefaultView *exceptionView;
@end @end
...@@ -63,14 +62,18 @@ ...@@ -63,14 +62,18 @@
#pragma mark - 登录成功后刷新 #pragma mark - 登录成功后刷新
- (void)needUpdateAiCoach { - (void)needUpdateAiCoach {
[WKWebView deleteWebCache]; NSHTTPCookie *sidCookie = nil;
for (NSHTTPCookie *cookie in [NSHTTPCookieStorage sharedHTTPCookieStorage].cookies) {
// 延迟的时间 // connect.sid是后台下发的cookie字段
int64_t delayInSeconds = 3.0; if ([cookie.name isEqualToString:@"connect.sid"]) {
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES]; sidCookie = cookie;
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ break;;
[self.aiWebView reload]; }
}); }
// 将APP获取的cookie同步给wkwebview容器里面的cookie(wkwebview存在cookie不同步的巨坑,该同步API在iOS 11及以后支持)
[self.aiWebView.configuration.websiteDataStore.httpCookieStore setCookie:sidCookie completionHandler:^{
[self.aiWebView loadRequest:self.request];
}];
} }
- (void)startOpen { - (void)startOpen {
...@@ -109,6 +112,7 @@ ...@@ -109,6 +112,7 @@
DSLog(@"加载失败:%@", error); DSLog(@"加载失败:%@", error);
} }
#pragma mark - WKScriptMessageHandler
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message { - (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
if ([message.name isEqualToString:@"AppModel"]) { if ([message.name isEqualToString:@"AppModel"]) {
NSDictionary *bodyDic = message.body; NSDictionary *bodyDic = message.body;
...@@ -117,34 +121,18 @@ ...@@ -117,34 +121,18 @@
int type = [bodyDic[@"type"] intValue]; int type = [bodyDic[@"type"] intValue];
if (type == 1) { // 未登录点击开启 if (type == 1) { // 未登录点击开启
[self startOpen]; [self startOpen];
// 注入js代码用于强制刷新小梦睡眠
NSString *jsCallBack = @"window.parent.location.reload()";
[self.aiWebView evaluateJavaScript:jsCallBack completionHandler:^(id _Nullable result, NSError * _Nullable error) {
[self.aiWebView loadRequest:self.request];
DSLog(@"注入成功...");
if (error) {
DSLog(@"err is %@", error.domain);
}
}];
} }
} }
// if ([message.name isEqualToString:@"xxx"]) {
// NSDictionary *jsData = message.body;
// NSLog(@"%@", message.name);
//读取js function的字符串
// NSString *jsFunctionString = jsData[@"result"];
// //拼接调用该方法的js字符串(convertDictionaryToJson:方法将NSDictionary转成JSON格式的字符串)
// NSString *jsonString = [NSDictionary convertDictionaryToJson:@{@"test":@"123", @"data":@"666"}];
// NSString *jsCallBack = [NSString stringWithFormat:@"(%@)(%@);", jsFunctionString, jsonString];
// //执行回调
// [self.weWebView evaluateJavaScript:jsCallBack completionHandler:^(id _Nullable result, NSError * _Nullable error) {
// if (error) {
// NSLog(@"err is %@", error.domain);
// }
// }];
// }
}
// js调用alert
- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler {
UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"alert" message:@"JS调用alert" preferredStyle:UIAlertControllerStyleAlert];
[alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
completionHandler();
}]];
[self presentViewController:alert animated:YES completion:NULL];
DSLog(@"message:%@", message);
} }
#pragma mark - lazy #pragma mark - lazy
...@@ -168,7 +156,6 @@ ...@@ -168,7 +156,6 @@
_aiWebView.backgroundColor = DSWhite; _aiWebView.backgroundColor = DSWhite;
_aiWebView.UIDelegate = self; _aiWebView.UIDelegate = self;
_aiWebView.hidden = YES; _aiWebView.hidden = YES;
[_aiWebView debugViewShowBorder];
_aiWebView.scrollView.bounces = NO; _aiWebView.scrollView.bounces = NO;
[_aiWebView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil]; [_aiWebView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
_aiWebView.navigationDelegate = self; _aiWebView.navigationDelegate = self;
...@@ -176,7 +163,7 @@ ...@@ -176,7 +163,7 @@
_aiWebView.scrollView.showsHorizontalScrollIndicator = NO; _aiWebView.scrollView.showsHorizontalScrollIndicator = NO;
// 解决页面顶部出现白色问题 // 解决页面顶部出现白色问题
_aiWebView.scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever; _aiWebView.scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
self.request = [NSURLRequest requestWithURL:[NSURL URLWithString:AICoachURL]]; self.request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:AICoachURL] cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:10.0];
[_aiWebView loadRequest:self.request]; [_aiWebView loadRequest:self.request];
} }
return _aiWebView; return _aiWebView;
......
...@@ -35,7 +35,10 @@ ...@@ -35,7 +35,10 @@
UIButton *dailyTaskBtn = [UIButton new]; UIButton *dailyTaskBtn = [UIButton new];
[dailyTaskBtn addTarget:self action:@selector(jumpToDailyTaskPage) forControlEvents:UIControlEventTouchUpInside]; [dailyTaskBtn addTarget:self action:@selector(jumpToDailyTaskPage) forControlEvents:UIControlEventTouchUpInside];
[dailyTaskBtn dk_setImage:DKImagePickerWithNames(@"ic_home_meirirw", @"dk_ic_home_meirirw", @"ic_home_meirirw") forState:UIControlStateNormal]; [dailyTaskBtn dk_setImage:DKImagePickerWithNames(@"ic_home_meirirw", @"dk_ic_home_meirirw", @"ic_home_meirirw") forState:UIControlStateNormal];
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:dailyTaskBtn];; self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:dailyTaskBtn];
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
[self addScaleAnimtaionWithView:dailyTaskBtn];
});
[self.view addSubview:self.homeTV]; [self.view addSubview:self.homeTV];
[self.view addSubview:self.noisePlayBar]; [self.view addSubview:self.noisePlayBar];
...@@ -63,6 +66,25 @@ ...@@ -63,6 +66,25 @@
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(needUpdate) name:NeedUpdateHomePage object:nil]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(needUpdate) name:NeedUpdateHomePage object:nil];
} }
#pragma mark - 先放大,再缩小
- (void)addScaleAnimtaionWithView:(UIView *)view {
// 放大效果,并回到原位
CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"transform.scale"];
// 速度控制函数,控制动画运行的节奏
animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
// 执行时间
animation.duration = 0.2;
// 执行次数
animation.repeatCount = 1;
// 完成动画后会回到执行动画之前的状态
animation.autoreverses = YES;
// 初始伸缩倍数
animation.fromValue = [NSNumber numberWithFloat:0.9];
// 结束伸缩倍数
animation.toValue = [NSNumber numberWithFloat:1.1];
[view.layer addAnimation:animation forKey:nil];
}
- (void)viewDidDisappear:(BOOL)animated { - (void)viewDidDisappear:(BOOL)animated {
[super viewDidDisappear:animated]; [super viewDidDisappear:animated];
......
支持 Markdown 格式
你添加了 0 到此讨论。请谨慎行事。
Finish editing this message first!