LoginSignup
46
48

More than 5 years have passed since last update.

iOS上にHTTPサーバを立ち上げる方法

Last updated at Posted at 2014-07-16

背景

Romoハッカソンで3DSからRomoを操作できるようにした時に、iOS端末内でHTTPサーバを動かすようにしました。その時のメモです。Objective-Cでごめんなさい。

Podfile

1からHTTPサーバ作るのなんてとても大変なので、CocoaPodsで使えるものを探しました。ルーティングの設定もしたかったので、Add-On的なものが入っています。

pod 'CocoaHTTPServer'
pod 'RoutingHTTPServer' 

HTTPサーバインスタンスの作成

AppDelegate.h内に以下を追加します。これはサンプルにあるのをそのまま使います。

AppDelegate.h
#import <RoutingHTTPServer/RoutingHTTPServer.h>
/* HTTPサーバーインスタンス */
@property (strong, nonatomic) RoutingHTTPServer *httpServer;

HTTPサーバの設定と起動を行います。

HTTPサーバの設定をします。サンプルほぼそのままです。content-typeを明示しないとルーティング時のレスポンスを返す際に、3DSで このファイルは読み込めません とエラーが出てしまっていたでそこだけ対応します。

AppDelegate.m
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    httpServer = [[RoutingHTTPServer alloc] init];

    // ポート未指定の場合ランダムで設定されるので、適当なポート番号を指定する
    [httpServer setPort:SERVER_PORT];

    // ドキュメントルートに「htdocs」を指定する
    [httpServer setDocumentRoot:[[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"htdocs"]];
    // Content-Typeを明示
    [httpServer setDefaultHeader:@"content-type" value:@"text/html"];

    //ルーティングの設定
    [self setupRoutes];

    // HTTPサーバーを起動する
    [self startServer];
    return YES;
}

ルーティングの設定をします

httpServerに対して、ルーティングの設定を行います。http://{ServerURL}/drive/LEDにアクセスされた場合に、LED!と返しつつ、なんらかのコードが実行できる例です。

AppDelegate.m
- (void)setupRoutes {
    [httpServer get:@"/drive/LED" withBlock:^(RouteRequest *request, RouteResponse *response) {
        /* とりあえずメッセージを返す */
        [response respondWithString:@"LED!"];
        /* 必要に応じてなんらかのコードを書く */
    }];

これで出来ること

自分のアプリ内にサーバ立てられるので、XSSによる制限を回避する場合とかには有効なのかもしれません。申請が通るかはわかりませんが...。

コメントによるとAppStoreの審査を通った実績は有るようです。

46
48
4

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
46
48