美文网首页iOS机制
iOS实现webView附件预览

iOS实现webView附件预览

作者: 玉思盈蝶 | 来源:发表于2022-04-10 16:40 被阅读0次

    我们有个需求需要实现拦截点击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 @"";
    }
    

    相关文章

      网友评论

        本文标题:iOS实现webView附件预览

        本文链接:https://www.haomeiwen.com/subject/bnivsrtx.html