iOS加載本地HTML的兩種方式(文件、本地服務(wù)器)

第一種:以文件的形式加載HTML資源

優(yōu)點(diǎn):最簡單
缺點(diǎn):有些HTML中的樣式不支持file:在樣式和功能上有缺失
作法:
  1.將所有的H5文件(含html、css、js、images)都放入一個(gè)文件夾中(例如:HtmlFile)
  2.將這個(gè)文件夾以相對路徑的方式導(dǎo)入到工程代碼中(例如放到Resource文件夾下)
  3.獲取本地的文件路徑:(例如打開首頁:index.html)
選相對路徑.png

放入工程后.png
/**參數(shù)1:index 是要打開的html的名稱
    參數(shù)2:html 是index的后綴名
    參數(shù)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]];

第二種:搭建本地服務(wù)器,通過本地服務(wù)器加載本地HTML文件

     優(yōu)點(diǎn):同網(wǎng)絡(luò)服務(wù)器加載的樣式和功能完全一致
      缺點(diǎn):需要額外搭建本地服務(wù)器、HTML文件的路徑需要處理
      做法:
          1.用CocoaHTTPServer搭建本地服務(wù)器 pod 'CocoaHTTPServer'
          2.引入HTML文件,需要注意index.html要與css樣式和其他功能包在一個(gè)路徑下
         3.需要處理本地服務(wù)器的啟動(dòng)和關(guān)閉
AppDelegate中:

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

#import <HTTPServer.h>//本地服務(wù)器
#import "BYHomeWebVC.h"http://首頁WebVC
/**本地服務(wù)器*/
@property (strong, nonatomic) HTTPServer *httpServer;
/**是否啟動(dòng)了本地服務(wù)器*/
@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];
    //開啟本地服務(wù)器
    [self openServer];
    //跳轉(zhuǎn)到首頁WebVC
    BYHomeWebVC *homeWebVC = [[BYHomeWebVC alloc]init];
    self.window.rootViewController = homeWebVC;
    [self.window makeKeyAndVisible];

    return YES;
}
- (void)openServer {//開啟本地服務(wù)器
    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(@"服務(wù)器路徑:%@", webPath);
    _startServer = [self startServer];
}
- (BOOL)startServer{//啟動(dòng)服務(wù)
    BOOL ret = NO;
    NSError *error = nil;
    if( [self.httpServer start:&error]){
        NSLog(@"HTTP服務(wù)器啟動(dòng)成功端口號為: %hu", [_httpServer listeningPort]);
        self.serverPort = [NSString stringWithFormat:@"%d",[self.httpServer listeningPort]];
        ret = YES;
    }else{
        NSLog(@"啟動(dòng)HTTP服務(wù)器出錯(cuò): %@", error);
    }
    return ret;
}
- (void)stopServer{//停止服務(wù)
    if (self.httpServer != nil){
        [self.httpServer stop];
        _startServer = NO;
    }
}
- (void)applicationDidEnterBackground:(UIApplication *)application {//進(jìn)入后臺
    if (_startServer){//停止本地服務(wù)器
        [self stopServer];
    }
}
- (void)applicationWillEnterForeground:(UIApplication *)application {//將要進(jìn)入前臺
    if (!_startServer){
        _startServer = [self startServer];
    }
}

//首頁WebVC

#import "BYHomeWebVC.h"
#import <WebKit/WebKit.h>
#import "AppDelegate.h"
#import "BYVideoDetailVC.h"http://視頻詳情頁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對象,在為網(wǎng)頁加載完成時(shí)注入
    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:網(wǎng)頁URL和內(nèi)容變化的時(shí)候調(diào)用
    NSURL *url = [navigationAction.request URL];
    NSLog(@"shouldStartLoadWithRequest = %@", [url absoluteString]);
    if (YES == [self willGotoOutSideWebViewByKey:@"skipType=goNative" observerUrl:url]) {
        NSDictionary *parameterDict = [self analysisParameterWithURL:url];
        NSLog(@"shouldStartLoadWithRequest-參數(shù):%@",parameterDict);
        BYVideoDetailVC *videoDetailVC = [[BYVideoDetailVC alloc]init];
        videoDetailVC.videoType = BYSafeStr([parameterDict objectForKey:@"courseType"]);//視頻的類型:1點(diǎn)播、2直播
        videoDetailVC.courseId = BYSafeStr([parameterDict objectForKey:@"id"]);//當(dāng)前課程id 6a328f708d2f4431aeb9c670c13bba6a
        NSString *token = BYSafeStr([parameterDict objectForKey:@"token"]);//@"4cde92f1e8fd159d3d5205a057861b46";
        [[NSUserDefaults standardUserDefaults] setObject:token forKey:@"userToken"];
        [[NSUserDefaults standardUserDefaults] synchronize];
        videoDetailVC.chapterId = BYSafeStr([parameterDict objectForKey:@"charpterId"]);//@"";//當(dāng)前章節(jié)的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所有參數(shù)轉(zhuǎn)化為字典
    NSMutableDictionary *paraDic= [[NSMutableDictionary alloc]init];
    //傳入url創(chuàng)建url組件類
    NSURLComponents *urlComponents = [[NSURLComponents alloc] initWithString:url.absoluteString];
    //回調(diào)遍歷所有參數(shù),添加入字典
    [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
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容