iOS加载本地HTML的两种方式(文件、本地服务器)

第一种:以文件的形式加载HTML资源

 

优点:最简单
缺点:有些HTML中的样式不支持file:在样式和功能上有缺失
作法:
  1.将所有的H5文件(含html、css、js、images)都放入一个文件夹中(例如:HtmlFile)
  2.将这个文件夹以相对路径的方式导入到工程代码中(例如放到Resource文件夹下)
  3.获取本地的文件路径:(例如打开首页:index.html)

 

选相对路径.png

 

 

放入工程后.png

 

/**参数1:index 是要打开的html的名称
    参数2:html 是index的后缀名
    参数3:HtmlFile/app/index 是文件夹的路径
*/
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"index" ofType:@"html" inDirectory:@"HtmlFile/app/index"];
 NSURL *pathURL = [NSURL fileURLWithPath:filePath];
  [_webView loadRequest:[NSURLRequest requestWithURL:pathURL]];

第二种:搭建本地服务器,通过本地服务器加载本地HTML文件

 

     优点:同网络服务器加载的样式和功能完全一致
      缺点:需要额外搭建本地服务器、HTML文件的路径需要处理
      做法:
          1.用CocoaHTTPServer搭建本地服务器 pod 'CocoaHTTPServer'
          2.引入HTML文件,需要注意index.html要与css样式和其他功能包在一个路径下
         3.需要处理本地服务器的启动和关闭

 

AppDelegate中:

      /**本地服务器端口*/
@property (nonatomic,copy) NSString *serverPort;

#import <HTTPServer.h>//本地服务器
#import "BYHomeWebVC.h"//首页WebVC
/**本地服务器*/
@property (strong, nonatomic) HTTPServer *httpServer;
/**是否启动了本地服务器*/
@property(nonatomic,assign)BOOL startServer;

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    self.window = [[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
    self.window.backgroundColor = [UIColor whiteColor];
    //开启本地服务器
    [self openServer];
    //跳转到首页WebVC
    BYHomeWebVC *homeWebVC = [[BYHomeWebVC alloc]init];
    self.window.rootViewController = homeWebVC;
    [self.window makeKeyAndVisible];

    return YES;
}
- (void)openServer {//开启本地服务器
    self.httpServer=[[HTTPServer alloc]init];
    [self.httpServer setType:@"_http._tcp."];
    [self.httpServer setPort:6080];
    NSString *webPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"HtmlFile"];
    [self.httpServer setDocumentRoot:webPath];
    NSLog(@"服务器路径:%@", webPath);
    _startServer = [self startServer];
}
- (BOOL)startServer{//启动服务
    BOOL ret = NO;
    NSError *error = nil;
    if( [self.httpServer start:&error]){
        NSLog(@"HTTP服务器启动成功端口号为: %hu", [_httpServer listeningPort]);
        self.serverPort = [NSString stringWithFormat:@"%d",[self.httpServer listeningPort]];
        ret = YES;
    }else{
        NSLog(@"启动HTTP服务器出错: %@", error);
    }
    return ret;
}
- (void)stopServer{//停止服务
    if (self.httpServer != nil){
        [self.httpServer stop];
        _startServer = NO;
    }
}
- (void)applicationDidEnterBackground:(UIApplication *)application {//进入后台
    if (_startServer){//停止本地服务器
        [self stopServer];
    }
}
- (void)applicationWillEnterForeground:(UIApplication *)application {//将要进入前台
    if (!_startServer){
        _startServer = [self startServer];
    }
}

 

//首页WebVC

#import "BYHomeWebVC.h"
#import <WebKit/WebKit.h>
#import "AppDelegate.h"
#import "BYVideoDetailVC.h"//视频详情页VC

@interface BYHomeWebVC ()<WKUIDelegate,WKNavigationDelegate>
/**WKWebView*/
@property (strong, nonatomic)WKWebView *webView;

@end
@implementation BYHomeWebVC
#pragma mark- init初始化
- (void)viewDidLoad {
    [super viewDidLoad];
    [self setWebview];
    [self loadLocalHttpServer];
}
- (void)setWebview{
    self.view.backgroundColor = [UIColor colorWithRed:41.0/255.0 green:46.0/255.0 blue:63.0/255.0 alpha:1.0];
    NSString *js = @"document.getElementsByClassName('libao')[0].style.display='none';document.getElementsByClassName('mengceng_1')[0].style.display='none';document.getElementById('icon_7724').style.display='none'";
    WKUserScript *script = [[WKUserScript alloc] initWithSource:js injectionTime:WKUserScriptInjectionTimeAtDocumentStart  forMainFrameOnly:YES];//初始化WKUserScript对象,在为网页加载完成时注入
    WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
    [config.userContentController addUserScript:script];
    self.webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, BYStatusBar_H, BYScreenWidth, BYScreenHeight - BYStatusBar_H) configuration:config];
    self.webView.backgroundColor = [UIColor colorWithRed:41.0/255.0 green:46.0/255.0 blue:63.0/255.0 alpha:1.0];;
    self.webView.opaque = NO;
    [self.view addSubview:self.webView];
    self.webView.UIDelegate = self;
    self.webView.navigationDelegate = self;
}
- (BOOL)loadLocalHttpServer{
    AppDelegate *appd = (AppDelegate *)[UIApplication sharedApplication].delegate;
    NSString *port = appd.serverPort;
    if (port == nil) {
        return NO;
    }
    NSString *str = [NSString stringWithFormat:@"http://localhost:%@", port];
    NSURL *url = [NSURL URLWithString:str];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    [self.webView loadRequest:request];
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    return YES;
}
- (void)webView:(WKWebView *)webView didFinishNavigation:(null_unspecified WKNavigation *)navigation{
    [MBProgressHUD hideHUDForView:self.view animated:YES];
}
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler{//WKWebView:网页URL和内容变化的时候调用
    NSURL *url = [navigationAction.request URL];
    NSLog(@"shouldStartLoadWithRequest = %@", [url absoluteString]);
    if (YES == [self willGotoOutSideWebViewByKey:@"skipType=goNative" observerUrl:url]) {
        NSDictionary *parameterDict = [self analysisParameterWithURL:url];
        NSLog(@"shouldStartLoadWithRequest-参数:%@",parameterDict);
        BYVideoDetailVC *videoDetailVC = [[BYVideoDetailVC alloc]init];
        videoDetailVC.videoType = BYSafeStr([parameterDict objectForKey:@"courseType"]);//视频的类型:1点播、2直播
        videoDetailVC.courseId = BYSafeStr([parameterDict objectForKey:@"id"]);//当前课程id 6a328f708d2f4431aeb9c670c13bba6a
        NSString *token = BYSafeStr([parameterDict objectForKey:@"token"]);//@"4cde92f1e8fd159d3d5205a057861b46";
        [[NSUserDefaults standardUserDefaults] setObject:token forKey:@"userToken"];
        [[NSUserDefaults standardUserDefaults] synchronize];
        videoDetailVC.chapterId = BYSafeStr([parameterDict objectForKey:@"charpterId"]);//@"";//当前章节的id
        videoDetailVC.vodeoPath = BYSafeStr([parameterDict objectForKey:@"path"]);//@"";//视频路径
        [self presentViewController:videoDetailVC animated:YES completion:nil];
        //        [self presentViewController:[[UINavigationController alloc] initWithRootViewController:videoDetailVC] animated:YES completion:nil];
        decisionHandler(WKNavigationActionPolicyCancel);
    }else{
        decisionHandler(WKNavigationActionPolicyAllow);
    }
}
- (BOOL)willGotoOutSideWebViewByKey:(NSString *)key observerUrl:(NSURL *)url {//判断url是否包含字符串key
    if (nil != url) {
        NSRange _rang = [[url absoluteString] rangeOfString:key];
        if(_rang.length > 0 && _rang.location != NSNotFound) {
            return YES;
        }
    }
    return NO;
}
- (NSDictionary *)analysisParameterWithURL:(NSURL *)url {//将url所有参数转化为字典
    NSMutableDictionary *paraDic= [[NSMutableDictionary alloc]init];
    //传入url创建url组件类
    NSURLComponents *urlComponents = [[NSURLComponents alloc] initWithString:url.absoluteString];
    //回调遍历所有参数,添加入字典
    [urlComponents.queryItems enumerateObjectsUsingBlock:^(NSURLQueryItem * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [paraDic setObject:obj.value forKey:obj.name];
    }];
    return paraDic;
}
- (void)dealloc{
    NSLog(@"已释放");
}


@end

 

HTML引入的路径.png


转载链接:https://www.jianshu.com/p/2b04d54eae20

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值