iOS 在一个UIScrollView上加载多个WKWebView

//
//  SSRealQuestionWKViewController.m
//  私塾家
//
//  Created by 欧阳荣 on 2020/10/16.
//  Copyright © 2020 Liew. All rights reserved.
//

#import "SSRealQuestionWKViewController.h"
#import "SSBookFileInfoModel.h"
#import "WKWebView+ConverToData.h"
#import "MBProgressHUD.h"
#import "MBProgressHUD+MJ.h"
#import "SSApExBookVersionModel.h"
#import <WebKit/WebKit.h>

@interface SSRealQuestionWKViewController ()<WKNavigationDelegate,WKUIDelegate,UIScrollViewDelegate>

@property (strong, nonatomic) UIButton *btnShare;
@property (nonatomic, strong) NSMutableDictionary *heightDic;
@property (nonatomic, strong) NSMutableArray *pathArr;
@property (nonatomic, strong) UILabel *pageLab;
@property (nonatomic, strong) NSMutableArray *webViewArr;
@property (strong, nonatomic) UIScrollView *mainScrollView;
@property (strong, nonatomic) WKWebView *currentWebView;

@end

@implementation SSRealQuestionWKViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = self.titleStr;
    self.heightDic = [[NSMutableDictionary alloc] init];
    UIBarButtonItem *rightBarItem = [[UIBarButtonItem alloc] initWithCustomView:self.btnShare];
    self.navigationItem.rightBarButtonItem = rightBarItem;
    [self getRealQuestionInfo:self.yearTermtrainId];
}

- (void)dealloc {
    for (WKWebView *webView in self.webViewArr) {
        [webView.scrollView removeObserver:self forKeyPath:@"contentSize" context:nil];
    }
}

#pragma mark - KVO

- (void)observeValueForKeyPath:(NSString *)keyPath
                      ofObject:(id)object
                        change:(NSDictionary *)change
                       context:(void *)context
{
    if ([object isKindOfClass:[UIScrollView class]] && [keyPath isEqual:@"contentSize"]) {
        // we are here because the contentSize of the WebView's scrollview changed.
        UIScrollView *scrollView = (UIScrollView *)object;
        NSLog(@"方法五 ###### New contentSize: %f x %f", scrollView.contentSize.width, scrollView.contentSize.height);
        WKWebView *webView = (WKWebView *)scrollView.superview;
        NSString *key = [NSString stringWithFormat:@"%ld",(long)webView.tag];
        //NSLog(@" --- webView: %@ --- tag: %ld",webView,webView.tag);
        NSInteger oldHeight = (NSInteger)[[self.heightDic objectForKey:key] floatValue];
        NSInteger newHeight = (NSInteger)scrollView.contentSize.height;
        NSLog(@" --- oldHeight: %ld - newHeight: %ld",(long)oldHeight, (long)newHeight);
        webView.height = newHeight;
        if (![self.heightDic objectForKey:key] || oldHeight != newHeight){
            [self.heightDic setObject:[NSNumber numberWithFloat:newHeight] forKey:key];
            [self reloadWebViews:self.webViewArr witnMainSrollView:self.mainScrollView];
        }
    }
}

- (void)reloadWebViews:(NSArray *)webViewArr witnMainSrollView:(UIScrollView *)mainSrollView{
    CGFloat top_Y = 0.0;
    for (WKWebView *webView in webViewArr) {
        webView.frame = CGRectMake(0, top_Y, kFullScreenWidth, webView.height);
        top_Y += webView.height;
    }
    self.mainScrollView.contentSize = CGSizeMake(kFullScreenWidth, top_Y);
}

#pragma mark - NetWork

-(void)getRealQuestionInfo:(NSString *)yearTermtrainId{
    
    NSDictionary *params = @{@"yearTermtrainId":yearTermtrainId};
    WEAKSELF(weakSelf);
    [XWHttpClient xw_postWithUrlString:HTTP_End_Path(@"/getRealQuestionInfo") Params:params DefaultHUD:NO SuccessBlock:^(id returnValue) {
        
        NSLog(@" --- 历年真题获取教材版本下的省市区时间筛选的真题文件 --- %@",returnValue);
        SSApExBookVersionData *tempModel = [SSApExBookVersionData mj_objectWithKeyValues:DicGetValue(returnValue, @"data")];
        for (NSString *path in tempModel.list) {
            SSBookFileModel *model = [[SSBookFileModel alloc] init];
            model.bookPath = path;
            [weakSelf.pathArr addObject:model];
        }
        CGFloat top_Y = 0;
        for (NSInteger i = 0; i < weakSelf.pathArr.count; i ++) {
            SSBookFileModel *model = weakSelf.pathArr[i];
            WKWebView *webView = [self createWebViewWithTag:i];
            webView.y = top_Y;
            top_Y += webView.height;
            NSString *imgUrl = [SSUtility getImageFullPathWithServerPath:model.bookPath];
            NSString *encodedString = (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes (kCFAllocatorDefault, (CFStringRef)imgUrl,(CFStringRef) @"!NULL,'()*+,-./:;=?@_~%#[]", NULL, kCFStringEncodingUTF8));
            NSURL *filePath = [NSURL URLWithString:encodedString];
            model.filePDFUrl = filePath;
            NSURLRequest *request1 = [NSURLRequest requestWithURL:filePath cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:10.f];
            [webView loadRequest:request1];
            [weakSelf.webViewArr addObject:webView];
            [webView.scrollView addObserver:self forKeyPath:@"contentSize" options:NSKeyValueObservingOptionNew context:nil];
            [weakSelf.mainScrollView addSubview:webView];
            if (i == 0) {
                self.currentWebView = webView;
            }
        }
        if (weakSelf.pathArr.count > 0) {
            weakSelf.pageLab.text = [NSString stringWithFormat:@"文件数:1/%lu",(unsigned long)weakSelf.pathArr.count];
            weakSelf.pageLab.hidden = NO;
        }
                
    } ErrorBlock:nil FailureBlock:nil];

}

#pragma mark - UIScrollViewDelegate
//tableView自动停止
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    //SSLog(@" --- scrollViewDidEndDecelerating --- ");
    [self getCurrentPageWithScrollView:scrollView];
}

/**
 手指拖动滑行
 @param decelerate 滑动明确位移返回NO,自动滑行一段位移返回YES
 */
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    //SSLog(@" --- scrollViewDidEndDragging --- ");
    if (!decelerate) [self getCurrentPageWithScrollView:scrollView];
}

- (void)getCurrentPageWithScrollView:(UIScrollView *)scrollView{

    CGFloat offSetY = scrollView.contentOffset.y;
    SSLog(@" --- getCurrentPageWithScrollView --- offSetY:%f",offSetY);
    NSInteger index = [self getIndexWithOffSetY:offSetY webViewArr:self.webViewArr];
    self.pageLab.text = [NSString stringWithFormat:@"文件数:%ld/%lu",(long)(index + 1),(unsigned long)self.pathArr.count];
    self.currentWebView = [self.webViewArr objectOrNilAtIndex:index];
    
}

- (NSInteger)getIndexWithOffSetY:(CGFloat)offsetY webViewArr:(NSArray *)webViewArr {
    NSInteger index = 0;
    CGFloat top_Y = 0.0;
    for (WKWebView *webView in webViewArr) {
        webView.frame = CGRectMake(0, top_Y, kFullScreenWidth, webView.height);
        top_Y += webView.height;
        if (offsetY > top_Y) { // 滑动超过了一页,就 +1;
            index ++;
        }
    }
    return index;
}

#pragma mark - Private Method

- (void)sharePdfWithWebPage {
    
    NSMutableDictionary * params = [NSMutableDictionary dictionary];
    SSBookFileModel *model = [self.pathArr objectOrNilAtIndex:self.currentWebView.tag];
    NSString *shareText = [NSString stringWithFormat:@"%@\n%@",[[self getFileName] substringWithRange:NSMakeRange(0,17)],self.subject];
    [params SSDKSetupWeChatParamsByText:shareText title:@"期末真题打印文件" url:model.filePDFUrl thumbImage:nil image:[UIImage imageNamed:@"Share_thumbImage"] musicFileURL:nil extInfo:nil fileData:nil emoticonData:nil sourceFileExtension:nil sourceFileData:nil type:SSDKContentTypeWebPage forPlatformSubType:SSDKPlatformSubTypeWechatSession];
    [ShareSDK share:SSDKPlatformSubTypeWechatSession
             parameters:params onStateChanged:^(SSDKResponseState state, NSDictionary *userData, SSDKContentEntity *contentEntity, NSError *error) {
        switch (state) {
            case SSDKResponseStateSuccess:{
                SSLog(@"分享成功");
            }
                break;
            case SSDKResponseStateFail:{
                SSLog(@"分享失败:%@",error.description);
            }
                break;
            case SSDKResponseStateCancel:

                break;
            default:
            break;
        }
     }];

}

- (void)shareFileWithPDFData:(NSData*)data fileName:(NSString *)fileName{
    
    if (data.length == 0) {
       SSAlertView *alertView = [[SSAlertView alloc] initWithTitle:@"PDF文件生成失败" titleColor:[UIColor blackColor] titleBackgroundColor:[UIColor whiteColor]];
       //添加按钮
       [alertView setButtonTitles:@[@"确定"]];
       [alertView setOnButtonClickHandle:^(SSAlertView *alertView, NSInteger buttonIndex) {
           [alertView dismiss];
       }];
       [alertView show];
       return;
    }

    NSString *title = [NSString stringWithFormat:@"小塾学伴-定制练习打印文件 %@.pdf",[fileName substringWithRange:NSMakeRange(0,17)]];
    NSMutableDictionary * params = [NSMutableDictionary dictionary];
    [params SSDKSetupWeChatParamsByText:nil title:title url:nil thumbImage:nil image:nil musicFileURL:nil extInfo:nil fileData:nil emoticonData:nil sourceFileExtension:@"pdf" sourceFileData:data type:SSDKContentTypeFile forPlatformSubType:SSDKPlatformSubTypeWechatSession];
    [ShareSDK share:SSDKPlatformSubTypeWechatSession
             parameters:params onStateChanged:^(SSDKResponseState state, NSDictionary *userData, SSDKContentEntity *contentEntity, NSError *error) {
        switch (state) {
            case SSDKResponseStateSuccess:{
                NSLog(@"分享成功");
            }
                break;
            case SSDKResponseStateFail:{
                NSLog(@"分享失败:%@",error.description);
              }
                break;
            case SSDKResponseStateCancel:
                break;
            default:
            break;
        }
     }];
    
}

-(NSString *)getFileName{
    NSString *dateString = [NSDate getDateStringByDate:[NSDate date]];
    NSString *timeString = [NSDate getTimeWithSecondStringByDate:[NSDate date]];
    NSString *typeString = @"真题练习";
    NSString *fullFileName = [NSString stringWithFormat:@"%@ %@-%@-%@.pdf",dateString,timeString,typeString,@"数学"];
    return fullFileName;
}

-(BOOL)creatFile:(NSString*)filePath{
    if (filePath.length==0) {
        return NO;
    }
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if ([fileManager fileExistsAtPath:filePath]) {
        return YES;
    }
    NSError *error;
    BOOL isSuccess = [fileManager createDirectoryAtPath:filePath withIntermediateDirectories:YES attributes:nil error:&error];
    if (error) {
        NSLog(@"creat File Failed:%@",[error localizedDescription]);
    }
    if (!isSuccess) {
        return isSuccess;
    }
    isSuccess = [fileManager createFileAtPath:filePath contents:nil attributes:nil];
    return isSuccess;
}

#pragma mark - Event Response

- (void)savePDFAndShare{
    
    if (![SSAuthorizeLoginManager isAppInstalledToPlatform:SharePlatformTypeOfWechatSession]) {
        [[SSCustomAlertView alloc] setAlertViewTitle:@"提示" andMessage:@"检测到您未安装微信,请先安装微信~" andhideAlertViewTimeOut:kDefaultAlertTime];
        return;
    }

    if (self.webViewArr.count == 0) {
        [[SSCustomAlertView alloc] setAlertViewTitle:@"提示" andMessage:@"无分享内容~" andhideAlertViewTimeOut:kDefaultAlertTime];
        return;
    }

    NSData *data = [self.currentWebView converToPDF];

    if (data.length >= kMaxShareLength) {
        [self sharePdfWithWebPage];
    }else {
        [self shareFileWithPDFData:data fileName:[self getFileName]];
    }
        
}

#pragma mark - Lazy Load

-(UIButton *)btnShare{
    if (!_btnShare) {
        _btnShare = [UIButton buttonWithType:UIButtonTypeCustom];
        _btnShare.frame = CGRectMake(0, 0, 80, 40);
        [_btnShare setTitle:@"发送到" forState:UIControlStateNormal];
        [_btnShare setTitleColor:UIColorFromHex(0x3BAF34) forState:UIControlStateNormal];
        [_btnShare.titleLabel setFont:[UIFont boldSystemFontOfSize:15]];
        [_btnShare setImage:[UIImage imageNamed:@"家长_周报_分享提分训练"] forState:UIControlStateNormal];
        [_btnShare layoutButtonWithEdgeInsetsStyle:SSButtonEdgeInsetsStyleRight imageTitleSpace:5];
        [_btnShare addTarget:self action:@selector(savePDFAndShare) forControlEvents:UIControlEventTouchUpInside];
    }
    return _btnShare;
}

- (NSMutableArray *)pathArr {
    if (_pathArr == nil) {
        _pathArr = [NSMutableArray array];
    }
    return _pathArr;;
}

- (UILabel *)pageLab {
    if (_pageLab == nil) {
        _pageLab = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 30)];
        _pageLab.centerX = kFullScreenWidth/2;
        _pageLab.centerY = kFullScreenHeight - kStatusBarAndNavigationBarHeight - BottomHeight - 25;
        _pageLab.textColor = [UIColor xy_createWithLightColor:UIColorFromHex(COLOR_393939) darkColor:UIColorFromHex(COLOR_FFFFFF)];
        _pageLab.backgroundColor = [UIColor xy_createWithLightColor:UIColorFromHex(COLOR_F1F3FA) darkColor:UIColorFromHex(COLOR_1B1B29)];
        _pageLab.textAlignment = NSTextAlignmentCenter;
        _pageLab.hidden = YES;
        _pageLab.font = FONTBOLD(12);
        [_pageLab setupCorneradius:15];
        [self.view addSubview:_pageLab];
    }
    return _pageLab;
}

- (WKWebView *)createWebViewWithTag:(NSInteger)tag {

    WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
    //创建设置对象
    WKPreferences *preference = [[WKPreferences alloc]init];
    //最小字体大小 当将javaScriptEnabled属性设置为NO时,可以看到明显的效果
    preference.minimumFontSize = 0;
    //设置是否支持javaScript 默认是支持的
    preference.javaScriptEnabled = YES;
    //在iOS上默认为NO,表示是否允许不经过用户交互由javaScript自动打开窗口
    preference.javaScriptCanOpenWindowsAutomatically = NO;
    config.preferences = preference;
    NSString *js = @" $('meta[name=description]').remove(); $('head').append( '' );";
    WKUserScript *wkUScript = [[WKUserScript alloc] initWithSource:js injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:NO];
    [config.userContentController addUserScript:wkUScript];
    WKWebView *webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, kFullScreenWidth, kFullScreenHeight) configuration:config];
    webView.scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    // UI代理
    webView.UIDelegate = self;
    webView.scrollView.scrollEnabled = NO;
    // 导航代理
    webView.navigationDelegate = self;
    // 是否允许手势左滑返回上一级, 类似导航控制的左滑返回
    webView.allowsBackForwardNavigationGestures = NO;
    webView.tag = tag;
    return webView;
    
}

- (NSMutableArray *)webViewArr {
    if (_webViewArr == nil) {
        _webViewArr = [NSMutableArray array];
    }
    return _webViewArr;
}

-(UIScrollView *)mainScrollView{
    if (!_mainScrollView) {
        _mainScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0,0,kFullScreenWidth, kFullScreenHeight-kStatusBarAndNavigationBarHeight)];
        _mainScrollView.pagingEnabled = NO;
        _mainScrollView.backgroundColor = [UIColor clearColor];
        _mainScrollView.showsVerticalScrollIndicator = YES;
        _mainScrollView.showsHorizontalScrollIndicator = NO;
        _mainScrollView.delegate = self;
        [self.view addSubview:_mainScrollView];
    }
    return _mainScrollView;
}

@end

猜你喜欢

转载自blog.csdn.net/qq_27247497/article/details/109166551
今日推荐