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

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章