iOS实现webView附件预览

我们有个需求需要实现拦截点击webView的附件进行附件下载和预览,安卓成功实现,iOS端一直下载不下来,最后发现问题在于webView代理拿到的url不全,和安卓对比发现安卓多了userId和token字段,iOS拦截下来没有该参数,导致下载失败。
后面想着直接用webView预览即可。但是不知道为什么有部分手机不支持预览,直接是打不来的状态。
最后使用navigationAction.targetFrame.isMainFrame实现附件预览。最后遇到返回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(@"内容开始返回");
}
 
- (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 @"";
}
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 212,029评论 6 492
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 90,395评论 3 385
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 157,570评论 0 348
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 56,535评论 1 284
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 65,650评论 6 386
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 49,850评论 1 290
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,006评论 3 408
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 37,747评论 0 268
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,207评论 1 303
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,536评论 2 327
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,683评论 1 341
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,342评论 4 330
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,964评论 3 315
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,772评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,004评论 1 266
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 46,401评论 2 360
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 43,566评论 2 349

推荐阅读更多精彩内容