hachinoBlog

hachinobuのエンジニアライフ

WebViewでHTMLを読み込んだ際に画像が表示されない現象

背景

久しぶりにHTMLつくってWebViewで表示させたらHTML内で表示するはずの画像が表示されなかった。

問題のコード

  NSString* htmlFileName = @"sample.html";
  NSString *filePath = [[NSBundle mainBundle] pathForResource:filename ofType:nil];
  NSString *html = [NSString stringWithContentsOfFile:filepath encoding:NSUTF8StringEncoding error:NULL];
  [_webView loadHTMLString:html baseURL:nil];

原因

原因はloadHTMLString:の第二引数であるbaseURLをnilにしていたため。

ここには画像とかリソースのパスを指定してあげなくてはならない。

解決コード

  NSString* htmlFileName = @"sample.html";
  NSString *filePath = [[NSBundle mainBundle] pathForResource:filename ofType:nil];
  NSString *html = [NSString stringWithContentsOfFile:filepath encoding:NSUTF8StringEncoding error:NULL];
  NSURL *resourceURL = [[NSBundle mainBundle] URLForResource:@"sample" withExtension:@"html"];
  [_webView loadHTMLString:html baseURL:resourceURL];

初歩的なことなのだけれど忘れてしまっていたのでメモ。