[iOS][Web]ネイティブWebアプリケーション(その3) | Cocoa練習帳

[iOS][Web]ネイティブWebアプリケーション(その3)

ほんの最初の一歩にしかならないと思うが。以前紹介したWebアプリケーションで、HTMLとObjective-Cでやり取りするのに挑戦した。




HTMLコンテンツにObjective-Cから値(日付)を設定する領域を用意する。




Date: <input name="demo" type="text"><br /> 



UIWebViewを管理するビューコントローラをUIWebViewDelegateに対応させる。




@interface ViewController : UIViewController <UIWebViewDelegate>
@end



デリゲートメッソドに、HTMLコンテンツの表題を取得するコードを追加する。




- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    NSString    *title = [webView stringByEvaluatingJavaScriptFromString:@"document.title"];
    NSLog(@"%@", title);
}



デリゲートメッソドに、HTMLコンテンツの要素demoの値を書き換えるコードを追加する。




- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    NSString    *date = [NSString stringWithFormat:
            @"document.getElementsByName('demo').item(0).value='%@'",
            [NSDate date]];
    [webView stringByEvaluatingJavaScriptFromString:date];
}



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

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


関連情報
UIWebView Class Reference

UIWebViewDelegate Protocol Reference