(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!」というアラートが表示されるだろう。