1、首先导入第三方
目录结构(删除了Samples文件夹)
导入库时选择create groups
成功导入后会报错
Multiple commands produce '/Users/xxx/Library/Developer/Xcode/DerivedData/3D_Touch-hkkuoykjtawrqcdogfwpdukvryhl/Build/Products/Debug-iphoneos/3D Touch.app/About.txt':
1) Target '3D Touch' (project '3D Touch') has copy command from '/Users/xxx/Desktop/CocoaHTTPServer-master/Vendor/CocoaAsyncSocket/About.txt' to '/Users/xxx/Library/Developer/Xcode/DerivedData/3D_Touch-hkkuoykjtawrqcdogfwpdukvryhl/Build/Products/Debug-iphoneos/3D Touch.app/About.txt'
2) Target '3D Touch' (project '3D Touch') has copy command from '/Users/xxx/Desktop/CocoaHTTPServer-master/Vendor/CocoaLumberjack/About.txt' to '/Users/xxx/Library/Developer/Xcode/DerivedData/3D_Touch-hkkuoykjtawrqcdogfwpdukvryhl/Build/Products/Debug-iphoneos/3D Touch.app/About.txt'
因为这两个文件有重复,才会报错的,将两个文件删除即可。
2、在appdelegate文件中开启服务,获取端口号
引入头文件,并定义两个全局变量
#import "HTTPServer.h"
#define webPath [[NSBundle mainBundle]pathForResource:@"content.html" ofType:nil]
@property (nonatomic) HTTPServer *localHttpServer;
@property (nonatomic) NSString *port;
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// 搭建本地服务器并启动
[self setupLocalHttpServer];
//导航
self.window.rootViewController = [[UINavigationController alloc]initWithRootViewController:[ViewController new]];
return YES;
}
#pragma mark - HTTP Server 搭建本地服务器并启动
- (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:端口号
#import <WebKit/WebKit.h>
@property (nonatomic) WKWebView *webView;
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
self.webView = [[WKWebView alloc] init];
//获取端口号,加载本地服务器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];
}