iOS 原生嵌套H5,混合開發

原理:

用UITableView做父視圖(加入MJRefresh刷新,pods導入),原生的view當做tableView的頭視圖,把H5(UIWebView or WKWebView)當做控件,放在cell里,禁止滾動,在JS交互里動態改變cell的高度,刷新tableView。


上代碼:

#import "WebViewController.h"

#import "MJRefresh.h"

#import <JavaScriptCore/JavaScriptCore.h> //UIWebView的JS交互

#import ?<WebKit/WebKit.h>

@interface ViewController ()<UITableViewDelegate, UITableViewDataSource, UIWebViewDelegate, WKNavigationDelegate, WKScriptMessageHandler>

{

UITableView *theTableView;

NSURLRequest *request; //H5鏈接

UIScrollView *scrollView; //WKWebView直接放在cell上會有顯示不全的問題,不知道為啥,WKWebView放在scrollView上,scrollView再放在cell上

}

@property (nonatomic, strong) MJRefreshNormalHeader *theMJHeader; //MJ刷新

@property (nonatomic, assign)CGFloat cellHeight; //記錄動態改變cell的高度

@property (nonatomic, strong) HomeHeaderView *headerView; //原生的view

@property (nonatomic, strong) UIWebView * webView;

@property (nonatomic, weak) JSContext * context; //UIWebView與JS交互

@property (nonatomic, strong) WKWebView *wkWebView;

@property (nonatomic, strong) WKWebViewConfiguration *configuration; //WKWebView與JS交互

@end

@implementation WebViewController

- (void)viewDidLoad{

[super viewDidLoad];

[self initUI];

[self refreshData]; // 請求數據

}

- (void)initUI{

theTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-64-49) style:UITableViewStylePlain];

theTableView.delegate = self;

theTableView.dataSource = self;

theTableView.showsVerticalScrollIndicator = NO;

theTableView.backgroundColor = [UIColor clearColor];

theTableView.separatorStyle = UITableViewCellSeparatorStyleNone;

//

UIView *view = [UIView new];

view.backgroundColor = [UIColor clearColor];

[theTableView setTableFooterView:view];

theTableView.tableHeaderView = self.headerView;

[self.view addSubview:theTableView];

theTableView.mj_header = self.theMJHeader;

NSString *URL = @“你的URL網址”;

request = [NSURLRequest requestWithURL:[NSURL URLWithString:URL]];

dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ //可能web加載需要時間,0.5秒延時

if (CurrentiOS < 8.0) {

[_webView loadRequest:request];

}else{

[_wkWebView loadRequest:request];

}

});

}

#pragma mark ---- ?UITableViewDelegate

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{

return 1;

}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cellId"];

if (cell == nil) {

cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cellId"];

if ([[[UIDevice currentDevice] systemVersion] floatValue] < 8.0 ) {

_webView = [[UIWebView alloc]initWithFrame:self.view.bounds];

_webView.backgroundColor = [UIColor whiteColor];

_webView.delegate = self;

_webView.scrollView.delegate = self;

_webView.scrollView.showsVerticalScrollIndicator = NO;//隱藏右側滾動條

_webView.scrollView.scrollEnabled = NO;//web禁止滑動

[cell.contentView addSubview:_webView];

}else{

scrollView = [UIScrollView new];

scrollView.frame = self.view.bounds;

scrollView.scrollEnabled = NO;//scrollView禁止滑動

[cell.contentView addSubview:scrollView];

_wkWebView = [[WKWebView alloc]initWithFrame:self.view.bounds];

_wkWebView.navigationDelegate = self;

_wkWebView.scrollView.showsVerticalScrollIndicator = NO;//隱藏右側滾動條

_wkWebView.scrollView.delegate = self;

_wkWebView.scrollView.scrollEnabled = NO;//web禁止滑動

[[_wkWebView configuration].userContentController addScriptMessageHandler:self name:@"AppModel"];//設置JS交互

[scrollView addSubview:_wkWebView];

}

}

return cell;

}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{

return _cellHeight;

}

#pragma mark ---- ?UIWebViewDelegate

-(void)webViewDidFinishLoad:(UIWebView *)webView{

DLog(@"UIWebView----網頁加載完畢");

[self.theMJHeader endRefreshing];

//獲取js的運行環境

_context=[webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];

_context[@"getAppData"] = ^(){

NSArray *array = [JSContext currentArguments];

NSDictionary *dic = [array[0] toDictionary];

//獲取web頁面傳的參數,進行下一步操作,此處通過傳出一個web的高度

//H5代碼? getAppData(參數);本例的參數是一個json對象

[self toNextVCOFH5:dic andWebView:_webView];

};

}

-(void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error{

DLog(@"UIWebView----網頁加載失敗/超時");

[self.theMJHeader endRefreshing];

}

#pragma mark ---- WKNavigationDelegate, WKScriptMessageHandler

-(void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{

DLog(@"WKWebView----網頁加載完畢");

[self.theMJHeader endRefreshing];

}

-(void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message{

if ([message.name isEqualToString:@"AppModel"]) {

DLog(@"message.body ---- %@", message.body);

NSDictionary *dic = [message.body dictionaryForKey:@"body"];

//獲取web頁面傳的參數,進行下一步操作,此處通過傳出一個web的高度

//H5代碼 ?window.webkit.messageHandlers.AppModel.postMessage(參數); 本例的參數是一個json對象

[self toNextVCOFH5:dic andWebView:_wkWebView];

}

}

- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error{

DLog(@"WKWebView----網頁加載失敗/超時");

[self.theMJHeader endRefreshing];

}

-(void)toNextVCOFH5:(NSDictionary *)dataDict andWebView:(id)webView{

CGFloat scale_screen = [UIScreen mainScreen].scale;//獲取屏幕的像素比例

NSInteger height = [[dataDict stringForKey:@"value"] integerValue]/scale_screen;

dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{

_cellHeight = height;

if ([webView isKindOfClass:[UIWebView class]]) {

_webView.frame = CGRectMake(0, 0, theTableView.frame.size.width, _cellHeight);

}

if ([webView isKindOfClass:[WKWebView class]]) {

scrollView.frame = CGRectMake(0, 0, theTableView.frame.size.width, _cellHeight);

scrollView.contentSize = CGSizeMake(theTableView.frame.size.width, _cellHeight);

_wkWebView.frame = CGRectMake(0, 0, theTableView.frame.size.width, _cellHeight);

}

[theTableView reloadData];

});

}

//刷新web

-(void)theWebReload{

if (request.URL) {

if ([[[UIDevice currentDevice] systemVersion] floatValue] < 8.0 ) {

[self.webView loadRequest:request];

}else{

[self.wkWebView loadRequest:request];

}

}else{

NSString *URL =@“你的url”;

request = [NSURLRequest requestWithURL:[NSURL URLWithString:URL]];

if ([[[UIDevice currentDevice] systemVersion] floatValue] < 8.0 ) {

[self.webView loadRequest:request];

}else{

[self.wkWebView loadRequest:request];

}

}

}

#pragma mark ---- headerView & 懶加載

-(HeaderView *)headerView{

if (!_headerView) {

_headerView = [[HeaderView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 390)];

}

return _headerView;

}

- (MJRefreshNormalHeader *)theMJHeader{

if(!_theMJHeader){

@weakify(self);

_theMJHeader = [MJRefreshNormalHeader headerWithRefreshingBlock:^{

@strongify(self);

[self refreshData];

[self theWebReload]; //刷新web

}];

_theMJHeader.automaticallyChangeAlpha = YES;

_theMJHeader.lastUpdatedTimeLabel.hidden = YES;

}

return _theMJHeader;

}

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • iOS開發系列--網絡開發 概覽 大部分應用程序都或多或少會牽扯到網絡開發,例如說新浪微博、微信等,這些應用本身可...
    lichengjin閱讀 3,721評論 2 7
  • 前言 關于UIWebView的介紹,相信看過上文的小伙伴們,已經大概清楚了吧,如果有問題,歡迎提問。 本文是本系列...
    CoderLF閱讀 9,017評論 2 12
  • 1、禁止手機睡眠[UIApplication sharedApplication].idleTimerDisabl...
    DingGa閱讀 1,144評論 1 6
  • iphone開發筆記 退回輸入鍵盤 - (BOOL) textFieldShouldReturn:(id)text...
    愛易寒曲易散閱讀 631評論 0 1
  • 百病成醫,看來我患病的次數還不夠多… 上禮拜傍晚,踏上滑板就屁顛屁顛的出去浪了,校內一路應該吸引不少眼球。嗯,之后...
    夕影西逝閱讀 240評論 0 0