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];
}