3
3

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.

 iOSでlocal htmlファイルを読み込むときに表示されなくてハマったのでメモ

Posted at

やりたいこと

とある画面のバックグラウンドでアニメーションを再生したい。
アニメーションネイティブ実装が面倒で、iOS, Android共通で表示したかったので、htmlファイルをwebviewで表示させる方法を選択しました。

完成イメージ

webviewイメージとしてはこんな感じ。
Simulator Screen Shot 2017.05.05 14.10.14.png

今回ハマったこと

出来たhtmlファイルはchrome等では表示されるのに、iOSでは読み込むと表示されませんでした。

結論から言うとhtml側のpathの問題でした。
xcodeに取り込んだ場合、フォルダ構成が異なるようです。

取り込んだhtmlソースのフォルダ

html, jsのフォルダ構成はこんな感じ。
スクリーンショット 2017-05-05 14.06.54.png

問題のhtmlファイルのパス

bubble.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">

    <link rel="stylesheet" type="text/css" href="css/common.css" media="all">
    <link rel="stylesheet" type="text/css" href="css/bubble.css" media="all">

    <script type="text/javascript" src="js/jquery.1.11.1.js"></script>
    <script type="text/javascript" src="js/bubble.js"></script>
</head>
<body>
    <div class="field"></div>
</body>
</html>

フォルダ構成的にhref="css/common.css", "js/bubble.js"で正しそうなのですが(実際はローカルにフォルダおいてchrome等で見てたときはこれでOKだった)、インストールされるアプリを見てみると、パッケージディレクトリでは異なるそうで、パスの変更が必要です。

以下、パスの変更版

bubble.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">

    <link rel="stylesheet" type="text/css" href="./common.css" media="all">
    <link rel="stylesheet" type="text/css" href="./bubble.css" media="all">

    <script type="text/javascript" src="./jquery.1.11.1.js"></script>
    <script type="text/javascript" src="./bubble.js"></script>
</head>
<body>
    <div class="field"></div>
</body>
</html>

veiwcontrollerの実装

ローカルファイルなのでwkwebviewにはしてません。

class ViewController: UIViewController {
    
    let bubblePath = Bundle.main.path(forResource: "bubble", ofType: "html")
    
    var webView: UIWebView!
    override func viewDidLoad() {
        super.viewDidLoad()
        webView = UIWebView(frame: self.view.frame)
        
        self.view.addSubview(webView)
        // Do any additional setup after loading the view, typically from a nib.
        
        let request = URL(fileURLWithPath: bubblePath!)
        let req = URLRequest(url: request)
        webView.loadRequest(req)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}

これでうまく表示されます( ❛⃘ ∨ ❜⃘⃘ )੭⁂

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?