13
13

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

PhoneGap(iOS)でカスタムURLスキームを実装する

Last updated at Posted at 2014-04-02

(App)-Info.plistでURL Typesを追加

InfoタブのURL Typesを、準備するURLスキームの分だけ追加する。

  • Identifier:アプリのBundle Identifier 例:com.bar.foo.HelloWorld
  • URL Schemes:用意するURLスキーム 例:SayHello
  • Iconはセットしなくても良い
  • RoleはEditor、Viewer、Noneから選べる。(iOSの方でも特に使っていないらしいので、とりあえずEditorにしておけば無難?)

この例では、「SayHello://」のようなURLスキームが出来たことになる。

PhoneGap (Cordova)

PhoneGapでは、特にカスタムURLスキームの設定は必要ない。
最初から、AppDelegate.mに下記のような実装が行われている。

AppDelegate.m
- (BOOL)application:(UIApplication*)application handleOpenURL:(NSURL*)url
{
    if (!url) {
        return NO;
    }

    // calls into javascript global function 'handleOpenURL'
    NSString* jsString = [NSString stringWithFormat:@"handleOpenURL(\"%@\");", url];
    NSLog(@"catch custome url scheme: %@", jsString);
    [self.viewController.webView stringByEvaluatingJavaScriptFromString:jsString];

    // all plugins will get the notification, and their handlers will be called
    [[NSNotificationCenter defaultCenter] postNotification:[NSNotification notificationWithName:CDVPluginHandleOpenURLNotification object:url]];

    return YES;
}

つまり、呼び出されたURLをそのまま、handleOpenURLというJavaScriptのグローバル関数に渡すので、それをJavaScript側で実装すれば良い。

例えば、こんな感じ。(CoffeeScriptだけど)

custom.coffee
window.handleOpenURL = (param) ->
	window.debug "handleOpenURL #{param}"
	[scheme, param] = param.toLowerCase().split("://")

	if scheme == "sayhello"
		alert "Hello, #{param}!"

アプリに複数のカスタムURLスキームを定義した場合でも、すべてのカスタムURLスキーム経由のアプリ起動がhandleOpenURLに来るので、ここでURLスキームを見て処理を振り分けてやると良さそう。

ちなみに、この例ではhandleOpenURLを、window.handleOpenURLにしているので、AppDelegate.mも下記のようにしておく。

AppDelegate.m
    NSString* jsString = [NSString stringWithFormat:@"window.handleOpenURL(\"%@\");", url];

あとは、Safariのアドレスバーに「SayHello://Ken」と入力して開くと、アプリが開き「Hello, Ken!」というアラートが表示されるだろう。

13
13
0

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
13
13

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?