iOS 利用CocoaHttpServer搭建手机本地服务器

1.导入第三方文件 (可以通过github下载)

2.导入所加载的html资源(切记此处需要选择绝对路径)

3.在Appdelegate中开启服务,设置端口号:


#import "HTTPServer.h"//本地服务器

@interface AppDelegate ()


/**本地服务器*/
@property (strong, nonatomic) HTTPServer *httpServer;
/**是否启动了本地服务器*/
@property(nonatomic,assign)BOOL startServer;


@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    [self openServer];//开启服务
    
    
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    UINavigationController *navi = [[UINavigationController alloc] initWithRootViewController:[[MainViewController alloc] init]];
    self.window.rootViewController = navi;
    [self.window makeKeyAndVisible];
    
    
    return YES;
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    if (_startServer){//停止本地服务器
        [self stopServer];
    }
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
    if (!_startServer){
        _startServer = [self startServer];
    }
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}


- (void)openServer {//开启本地服务器
    self.httpServer=[[HTTPServer alloc]init];
    [self.httpServer setType:@"_http._tcp."];
    [self.httpServer setPort:6080];
    NSString *webPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"gftyg"];
    
    NSFileManager *fileManager = [[NSFileManager alloc] init];
    NSLog(@"%@",webPath);
    
    if (![fileManager fileExistsAtPath:webPath]){
        NSLog(@"File path error!");
    }else{
        [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;
    }
}

4.访问本地服务器

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


#define screenWidth [UIScreen mainScreen].bounds.size.width
#define screenHeight [UIScreen mainScreen].bounds.size.height


@interface web3DViewController ()

/**WKWebView*/
@property (strong, nonatomic)WKWebView *webView;

@end

@implementation web3DViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self setWebview];
    [self loadLocalHttpServer];
}

- (void)setWebview{
    self.view.backgroundColor = [UIColor blackColor];
    self.webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, screenWidth, screenHeight)];
    [self.view addSubview:self.webView];
    
    return;
}
- (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];
    return YES;
}

猜你喜欢

转载自blog.csdn.net/KLong27/article/details/105818509