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

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值