iOS精品文章第三方工具类iOS开发笔记

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

2017-07-25  本文已影响1693人  c608

1、首先导入第三方
目录结构


屏幕快照 2017-07-25 下午1.39.53.png

然后导入你需要加载的html资源

17656F3B-8000-42A3-BA37-182924DAA1CF.png
屏幕快照 2017-07-25 下午1.50.46.png

2、在appdelegate中开启服务,获取端口号

屏幕快照 2017-07-25 下午1.54.56.png 屏幕快照 2017-07-25 下午1.55.04.png

pragma mark - 搭建本地服务器 并且启动

- (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:端口号

@interface ViewController ()
@property (weak, nonatomic) IBOutlet UIWebView *webView;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    //获取端口号,加载本地服务器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];

    // Do any additional setup after loading the view, typically from a nib.
}

因demo换本给丢了,给大家一个我当时写的时候参考链接参考链接

上一篇下一篇

猜你喜欢

热点阅读