[iOS]アプリケーション間通信 | Cocoa練習帳

[iOS]アプリケーション間通信

独自スキームとクリップボードを使ったアプリケーション間通信を試してみた。




URLスキーム「IPCServer.demo」で起動するサーバ・アプリケーションを用意する。スキームの登録方法は、[iOS][Web]ネイティブWebアプリケーション(その4)を参考にして欲しい。




サーバ・アプリケーションの画面にはラベルがある、クライアント・アプリケーションから情報を受け取ると、表示するようにする。




@implementation AppDelegate
...
- (BOOL)application:(UIApplication *)application
            openURL:(NSURL *)url
  sourceApplication:(NSString *)sourceApplication
         annotation:(id)annotation
{
    NSLog(@"%s, %@", __func__, url);
    if ([[url scheme] compare:@"IPCServer.demo"] == NSOrderedSame) {
        UIPasteboard    *pastedboard = [UIPasteboard pasteboardWithName:@"demo.IPCClient" create:NO];
        ViewController  *viewController = (ViewController *)self.window.rootViewController;
        [viewController setMessage:pastedboard.string];
        NSLog(@"pastedboard: %@", pastedboard.string);
        return YES;
    }
    return NO;
}
...
@end



クライアント・アプリケーションでは、テキストフィールドから取得した文字列をサーバに送信している。




@implementation ViewController
...
- (IBAction)send:(id)sender
{
    NSURL   *url = [NSURL URLWithString:@"IPCServer.demo://IPCServer.demo?key=value"];
    if ([[UIApplication sharedApplication] canOpenURL:url]) {
        UIPasteboard    *pastedboard = [UIPasteboard pasteboardWithName:@"demo.IPCClient" create:YES];
        pastedboard.persistent = YES;
        [pastedboard setString:self.textField.text];
        [[UIApplication sharedApplication] openURL:url];
    }
}
...
@end



シミュレータは、一度に一つしか起動できないと思うので、実機で試してほしい。




ソースコード
GitHubからどうぞ。

https://github.com/murakami/workbook/tree/master/ios/IPCServer - GitHub
https://github.com/murakami/workbook/tree/master/ios/IPCClient - GitHub


関連情報
Text, Web, and Editing Programming Guide for iOS



【Cocoa練習帳】
http://www.bitz.co.jp/weblog/

http://ameblo.jp/bitz/(ミラー・サイト)