長い道のりだったけど、ようやくiOSでHTTPサーバを立てることに成功!ちょっと感動したw
参考サイト様にはほんと感謝!
CocoaPodsのインストール
ターミナルを起動。
$ sudo gem update --system
$ sudo gem install -n /usr/local/bin cocoapods
$ pod setup
CocoaPodsを使ってCocoaHTTPServerとRoutingHTTPServerをインストール
ターミナルを起動。
$ cd ~/targetProject
「xcodeproj」ファイルがあるところ
Podfileファイルを作成
$ vi Podfile
ファイルの中身
※targetProjectはプロジェクト名(xcodeprojファイルの拡張子を含まないファイル名)
platform :ios,'10.3'
target 'targetProject'
pod 'CocoaHTTPServer'
pod 'RoutingHTTPServer'
pod 'AFNetworking','~> 2.0'
インストール
※おそらくupdateは要らないと思うけど一応
$ pod install
$ pod update
プロジェクトの起動
下記の名前のファイルができているので、今後はこれを起動
targetProject.xcworkspace
プログラム
AppDelegate.m
#import <RoutingHTTPServer/RoutingHTTPServer.h>
@interface AppDelegate ()
/**
HTTPサーバーインスタンス
*/
@property (strong, nonatomic) RoutingHTTPServer *httpServer;
@end
@implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.httpServer = [[RoutingHTTPServer alloc] init];
// ポート未指定の場合ランダムで設定されるので、適当なポート番号を設定
[self.httpServer setPort:50000];
// Content-Type設定
[self.httpServer setDefaultHeader:@"content-type" value:@"text/html"];
// ルーティング設定
[self.httpServer get:@"/world" withBlock:^(RouteRequest *request, RouteResponse *response)
{
// ブラウザに表示するメッセージ
[response respondWithString:@"Hello World"];
}];
// HTTPサーバーを起動
NSError *error;
if (![self.httpServer start:&error])
{
NSLog(@"Error starting HTTP Server: %@", error);
}
return YES;
}
パソコンのブラウザで表示してみる
「http://実機のIPアドレス:50000/world」にアクセスすれば「Hello World」と表示される!!
参考
iOSライブラリ管理ツール「CocoaPods」の使用方法
iOS上にHTTPサーバを立ち上げる方法
Cocoapods 1.0.0で注意すること