1、首先导入第三方
目录结构
然后导入你需要加载的html资源
2、在appdelegate中开启服务,获取端口号
pragma mark - 搭建本地服务器 并且启动
- (void)setupLocalHttpServer{
_localHttpServer = [[HTTPServer alloc] init];
[_localHttpServer setType:@"_http.tcp"];
NSFileManager *fileManager = [[NSFileManager alloc] init];
NSLog(@"%@",webPath);
if (![fileManager fileExistsAtPath:webPath]){
NSLog(@"File path error!");
}else{
NSString *webLocalPath = webPath;
[_localHttpServer setDocumentRoot:webLocalPath];
NSLog(@"webLocalPath:%@",webLocalPath);
[self startServer];
}
}
- (void)startServer
{
NSError *error;
if([_localHttpServer start:&error]){
NSLog(@"Started HTTP Server on port %hu", [_localHttpServer listeningPort]);
self.port = [NSString stringWithFormat:@"%d",[_localHttpServer listeningPort]];
//保存端口号,在调用的时候使用
NSUserDefaults *accountDefaults = [NSUserDefaults standardUserDefaults];
[accountDefaults setObject:self.port forKey:@"webPort"];
[accountDefaults synchronize];
}
else{
NSLog(@"Error starting HTTP Server: %@", error);
}
}
3、在UIViewController中加载webView
注意:链接必须是http://locoahost:端口号
@interface ViewController ()
@property (weak, nonatomic) IBOutlet UIWebView *webView;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
//获取端口号,加载本地服务器html
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"http://localhost:%@", [userDefaults objectForKey:@"webPort"]]];
NSLog(@"%@",[NSString stringWithFormat:@"http://localhost:%@", [userDefaults objectForKey:@"webPort"]]);
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[self.webView loadRequest:request];
// Do any additional setup after loading the view, typically from a nib.
}
因demo换本给丢了,给大家一个我当时写的时候参考链接参考链接