我們有個需求需要實現(xiàn)攔截點擊webView的附件進行附件下載和預覽咕幻,安卓成功實現(xiàn)渔伯,iOS端一直下載不下來,最后發(fā)現(xiàn)問題在于webView代理拿到的url不全谅河,和安卓對比發(fā)現(xiàn)安卓多了userId和token字段咱旱,iOS攔截下來沒有該參數(shù)确丢,導致下載失敗绷耍。
后面想著直接用webView預覽即可。但是不知道為什么有部分手機不支持預覽鲜侥,直接是打不來的狀態(tài)褂始。
最后使用navigationAction.targetFrame.isMainFrame實現(xiàn)附件預覽。最后遇到返回webView時候會遇到整體字體放大的情況描函,使用navigationAction.targetFrame.isMainFrame還遇到導航欄返回按鈕的處理崎苗。
好在最后這些問題都解決了,記錄下~~~
代碼如下:
#import "C2CustomWebVC.h"
#import "C2GetWhiteListReq.h"
@interface C2CustomWebVC ()<WKNavigationDelegate>
@property (nonatomic, copy) NSString *confValue;
@property (nonatomic, strong) NSArray *whiteListArray;// 白名單列表
@property (nonatomic, copy) NSString *recordUrl;
@property (nonatomic, assign) BOOL needReload;
@property (nonatomic, copy) NSString *url;
@property (nonatomic, strong) UIProgressView *progressView;
@property (nonatomic, strong) WKWebView *webView;
@property (nonatomic, strong) UIButton *closeButtion;
@property (nonatomic, strong) UIButton *backButton;
@end
@implementation C2CustomWebVC
- (instancetype)initWithUrl:(NSString *)url {
if (self = [super init]) {
self.url = url;
}
return self;
}
- (void)viewDidLoad {
[super viewDidLoad];
[self addWebViewObserver];
[self loadUrl];
[self buildUI];
}
- (void)viewWillAppear:(BOOL)animated{
[super viewWillAppear:animated];
[self configWebViewFrame];
}
- (void)dealloc{
[self prepareForClose];
}
- (void)addWebViewObserver{
if ([self isLocalUrl:self.url]) return;
[self.webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:NULL];
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{
// DLog(@"keyPath = %@, change = %@", keyPath, change);
if ([keyPath isEqualToString:@"estimatedProgress"]) {
if (object == self.webView) {
[self.progressView setAlpha:1.0f];
[self.progressView setProgress:self.webView.estimatedProgress animated:YES];
if(self.webView.estimatedProgress >= 1.0f) {
[UIView animateWithDuration:0.3 delay:0.3 options:UIViewAnimationOptionCurveEaseOut animations:^{
[self.progressView setAlpha:0.0f];
} completion:^(BOOL finished) {
[self.progressView setProgress:0.0f animated:NO];
}];
}
} else {
[super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
}
} else {
[super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
}
}
- (void)prepareForClose{
@try {
if ([self isLocalUrl:self.url]) return;
[self.webView removeObserver:self forKeyPath:@"estimatedProgress" context:NULL];
} @catch (NSException *exception) {
} @finally {
[self.webView removeFromSuperview];
}
}
- (void)configWebViewFrame {
CGFloat naviHeight = (self.navigationController && !self.navigationController.isNavigationBarHidden) ?kNavigationBarHeight:0;
CGFloat tabbarHeight = (self.tabBarController && self.navigationController.viewControllers.count==1)?kTabBarHeight:0;
self.progressView.hidden = [self isLocalUrl:self.url];
self.webView.frame = CGRectMake(0, 0, kScreenW, kScreenH - naviHeight - tabbarHeight);
}
- (BOOL)isLocalUrl:(NSString *)url {
return ![url hasPrefix:@"http"];
}
- (void)addLeftBarButtonItems {
self.backButton.frame = CGRectMake(0, 20+(kIs_iPhoneX?20:0), 55, 44);
self.closeButtion.frame = CGRectMake(55, 20+(kIs_iPhoneX?20:0), 35, 44);
UIBarButtonItem *backBarItem = [[UIBarButtonItem alloc] initWithCustomView:self.backButton];
UIBarButtonItem *closeBarItem = [[UIBarButtonItem alloc] initWithCustomView:self.closeButtion];
self.navigationItem.leftBarButtonItems = @[backBarItem,closeBarItem];
}
#pragma mark - WKNavigationDelegate
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
_recordUrl = navigationAction.request.URL.absoluteString;
if (navigationAction.targetFrame == nil || !navigationAction.targetFrame.isMainFrame) {
[webView loadRequest:navigationAction.request];
_needReload = YES;
decisionHandler(WKNavigationActionPolicyCancel);
return;
}
if (_needReload && ![_recordUrl containsString:@"file/loginlessDownloadFile"]) {
[webView loadRequest:navigationAction.request];
_needReload = NO;
}
decisionHandler(WKNavigationActionPolicyAllow);
}
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(null_unspecified WKNavigation *)navigation {
DLog(@"開始加載");
WEAKSELF
[self.webView evaluateJavaScript:@"navigator.userAgent" completionHandler:^(id result, NSError *error) {
NSString *userAgent = result;
//修改UserAgent
NSString *newUserAgent = [userAgent stringByAppendingString:@"C2Mobile/{1.0.0}"];
NSString *barHeight = [NSString stringWithFormat:@";statusBarHeight:%f",kStatusBarHeight];
newUserAgent = [newUserAgent stringByAppendingString:barHeight];
[wkSelf.webView setCustomUserAgent:newUserAgent];
}];
}
- (void)webView:(WKWebView *)webView didCommitNavigation:(null_unspecified WKNavigation *)navigation {
DLog(@"內(nèi)容開始返回");
}
- (void)webView:(WKWebView *)webView didFinishNavigation:(null_unspecified WKNavigation *)navigation {
DLog(@"加載完成");
// 禁用縮放
[self.webView evaluateJavaScript:[self disableZoom] completionHandler:nil];
// 禁用選中效果
[self.webView evaluateJavaScript:@"document.documentElement.style.webkitUserSelect='none'" completionHandler:nil];
[self.webView evaluateJavaScript:@"document.documentElement.style.webkitTouchCallout='none'" completionHandler:nil];
}
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error{
DLog(@"加載navi失敗 error : %@",error.description);
// WEAKSELF
// [self showNetworkErrorWithRetryBlock:^{
// [wkSelf loadUrl];
// }];
}
- (void)webView:(WKWebView *)webView didFailLoadWithError:(nonnull NSError *)error {
DLog(@"加載失敗 error : %@",error.description);
}
#pragma mark - Event
- (void)buildUI{
[self.navigationController.navigationBar setBackgroundImage:[[UIImage alloc] init] forBarMetrics:UIBarMetricsDefault];
self.navigationController.navigationBar.shadowImage = [[UIImage alloc]init];
if (@available(iOS 11.0, *)) {
self.webView.scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
} else {
self.edgesForExtendedLayout = UIRectEdgeNone;
}
[self.view addSubview:self.webView];
[self.webView addSubview:self.progressView];
[self addLeftBarButtonItems];
}
- (void)loadUrl{
if (!self.url.length) {
DLog(@"url is nil");
return;
}
self.webView.navigationDelegate = self;
NSString * url = [NSString convertCNtoUnicode:self.url];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
[self.webView loadRequest:request];
}
- (void)close {
[self backToLastPage];
}
-(BOOL)canGoBack{
return [self.webView canGoBack];
}
- (void)goBack{
[self.webView goBack];
}
- (void)actionPopBack{
if (self.webView.backForwardList.backList.count > 0) {
WKBackForwardListItem *item = self.webView.backForwardList.currentItem;
[self goBack];
[self.webView goToBackForwardListItem:[self.webView.backForwardList.backList firstObject]];
} else{
[self backToLastPage];
}
}
- (void)backToLastPage{
[self.navigationController popViewControllerAnimated:YES];
}
#pragma mark - Lazy Load
- (UIProgressView *)progressView {
if (!_progressView) {
_progressView = [[UIProgressView alloc]initWithFrame:CGRectMake(0, 0, kScreenW, 1)];
_progressView.trackTintColor = [UIColor clearColor];
_progressView.progressTintColor = kColor(40, 178, 254);
}
return _progressView;
}
- (WKWebView *)webView {
if (!_webView) {
WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc]init];
WKUserContentController *userCC = [[WKUserContentController alloc] init];
config.userContentController = userCC;
_webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, kScreenW, kScreenH - kNavigationBarHeight) configuration:config];
_webView.scrollView.showsVerticalScrollIndicator = NO;
_webView.scrollView.showsHorizontalScrollIndicator = NO;
if (@available(iOS 13.0,*)) {
config.defaultWebpagePreferences.preferredContentMode = WKContentModeMobile;
}
}
return _webView;
}
- (UIButton *)closeButtion{
if (!_closeButtion) {
_closeButtion = [UIButton buttonWithType:UIButtonTypeCustom];
[_closeButtion setTitle:@"關閉" forState:UIControlStateNormal];
_closeButtion.titleLabel.font = [UIFont systemFontOfSize:17];
_closeButtion.titleLabel.textAlignment = NSTextAlignmentCenter;
[_closeButtion setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[_closeButtion addTarget:self action:@selector(close) forControlEvents:UIControlEventTouchUpInside];
_closeButtion.exclusiveTouch = YES;
// _closeButtion.hidden = YES;
}
return _closeButtion;
}
- (UIButton *)backButton{
if (!_backButton) {
_backButton = [UIButton buttonWithType:UIButtonTypeCustom];
// UIImage *btnImage = [UIImage iconWithInfo:TBCityIconInfoMake(@"\U0000E623", 30, [UIColor blackColor])];
[_backButton setImage:[NSBundle bundleImageWithName:@"back"] forState:UIControlStateNormal];
[_backButton setTitle:@" 返回" forState:UIControlStateNormal];
_backButton.titleLabel.font = [UIFont systemFontOfSize:17];
[_backButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[_backButton addTarget:self action:@selector(actionPopBack) forControlEvents:UIControlEventTouchUpInside];
_backButton.exclusiveTouch = YES;
}
return _backButton;
}
#pragma mark - NSString
- (NSString *)disableZoom {
return @"var script = document.createElement('meta');"
"script.name = 'viewport';"
"script.content=\"width=device-width, user-scalable=no\";"
"document.getElementsByTagName('head')[0].appendChild(script);";
}
- (NSString *)webViewBridgeScript {
DLog(@"注入JS");
return @"";
}