【Objective-C】html・jqueryをネイティブで使う
ネイティブでhtml・jqueryファイルを用意して、UIWebViewに表示するときのメモです。
(環境:xcode5, iOS7)
// js・cssファイルを読み込む NSString* filePath1 = [[NSBundle mainBundle] pathForResource:@"jquery-ui" ofType:@"js"]; NSString *filePath2 = [[NSBundle mainBundle] pathForResource:@"jquery-1.9.1" ofType:@"js"]; NSString *filePath3 = [[NSBundle mainBundle] pathForResource:@"jquery-ui" ofType:@"css"]; NSString *script1 = [NSString stringWithContentsOfFile:filePath1 encoding:NSUTF8StringEncoding error:NULL]; NSString *script2 = [NSString stringWithContentsOfFile:filePath2 encoding:NSUTF8StringEncoding error:NULL]; NSString *script3 = [NSString stringWithContentsOfFile:filePath3 encoding:NSUTF8StringEncoding error:NULL]; [webView stringByEvaluatingJavaScriptFromString:script1]; [webView stringByEvaluatingJavaScriptFromString:script2]; [webView stringByEvaluatingJavaScriptFromString:script3]; // htmlの読み込み NSString *path = [[NSBundle mainBundle] pathForResource:@"sampleHTML" ofType:@"html"]; NSString *htmlStr = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:NULL]; [webView loadHTMLString:htmlStr baseURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] bundlePath]]];
上記のようにしてjqueryを読みこみます。
しかし、、デバッグしてもjqueryを読み込んでくれませんでした。
原因は、プロジェクトファイル > Build Phases > Copy Bundle Resources の中にjqueryファイルがなかったためです。
なので Copy Bundle Resources の下にある「+」を押して、プロジェクト内に入れたjqueryファイルを追加したら動きました!
以上です。