这篇文章主要介绍了IOS利用CocoaHttpServer搭建手机本地服务器的步骤,帮助大家更好的理解和学习使用ios开发,感兴趣的朋友可以了解下
这个路径是上传文件的存储路径
6.在适当的地方配置server启动。这里以AppDelegate为例
#import "AppDelegate.h"
#import <ifaddrs.h>
#import <arpa/inet.h>
#import "HTTPServer.h"
#import "DDLog.h"
#import "DDTTYLogger.h"
#import "MyHTTPConnection.h"
@interface AppDelegate ()
@property (nonatomic, strong) HTTPServer * httpServer;
@end
@implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
_httpServer = [[HTTPServer alloc] init];
[_httpServer setPort:1234];
[_httpServer setType:@"_http._tcp."];
// webPath是server搜寻HTML等文件的路径
NSString * webPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"web"];
[_httpServer setDocumentRoot:webPath];
[_httpServer setConnectionClass:[MyHTTPConnection class]];
NSError *err;
if ([_httpServer start:&err]) {
NSLog(@"port %hu",[_httpServer listeningPort]);
}else{
NSLog(@"%@",err);
}
NSString *ipStr = [self getIpAddresses];
NSLog(@"ip地址 %@", ipStr);
return YES;
}
- (NSString *)getIpAddresses{
NSString *address = @"error";
struct ifaddrs *interfaces = NULL;
struct ifaddrs *temp_addr = NULL;
int success = 0;
// retrieve the current interfaces - returns 0 on success
success = getifaddrs(&interfaces);
if (success == 0)
{
// Loop through linked list of interfaces
temp_addr = interfaces;
while(temp_addr != NULL)
{
if(temp_addr->ifa_addr->sa_family == AF_INET)
{
// Check if interface is en0 which is the wifi connection on the iPhone
if([[NSString stringWithUTF8String:temp_addr->ifa_name] isEqualToString:@"en0"])
{
// Get NSString from C String
address = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr)];
}
}
temp_addr = temp_addr->ifa_next;
}
}
// Free memory
freeifaddrs(interfaces);
return address;
}
7.运行后,控制台会打印出端口号和ip,在电脑端浏览器里输入ip+端口号访问即可,如果成功的话会看到如下界面:
8.如果上传成功,网页上会出现上传的文件名,可以在沙盒里验证文件是否上传成功
以上就是IOS利用CocoaHttpServer搭建手机本地服务器的详细内容,更多关于IOS用CocoaHttpServer搭建服务器的资料请关注编程学习网其它相关文章!
沃梦达教程
本文标题为:IOS利用CocoaHttpServer搭建手机本地服务器
猜你喜欢
- Android MaterialButton使用实例详解(告别shape、selector) 2023-06-16
- 最好用的ios数据恢复软件:PhoneRescue for Mac 2023-09-14
- 作为iOS开发,这道面试题你能答出来,说明你基础很OK! 2023-09-14
- SurfaceView播放视频发送弹幕并实现滚动歌词 2023-01-02
- Android实现监听音量的变化 2023-03-30
- Android studio实现动态背景页面 2023-05-23
- Flutter实现底部和顶部导航栏 2022-08-31
- 详解flutter engine 那些没被释放的东西 2022-12-04
- iOS 对当前webView进行截屏的方法 2023-03-01
- Android实现轮询的三种方式 2023-02-17
