10
5

More than 1 year has passed since last update.

【Swift】ローカルのHTMLとCSSをWebViewに表示する

Posted at

はじめに

今回はローカルにあるindex.htmlstyle.cssをWKWebViewで読み込む方法を紹介します。
スクリーンショット 2022-07-19 23.26.05.png

実装

index.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="style.css">
    <title>Document</title>
</head>
<body>
    <div class="box26">
        <span class="box-title">POINT</span>
        <p>これはSwiftのWKWebViewでローカルにあるHTMLとCSSを読み込むテストです。</p>
    </div>
</body>
</html>
style.css
.box26 {
    position: relative;
    margin: 2em 0;
    padding: 0.5em 1em;
    border: solid 3px #95ccff;
    border-radius: 8px;
}
.box26 .box-title {
    position: absolute;
    display: inline-block;
    top: -13px;
    left: 10px;
    padding: 0 9px;
    line-height: 1;
    font-size: 19px;
    background: #FFF;
    color: #95ccff;
    font-weight: bold;
}
.box26 p {
    margin: 0; 
    padding: 0;
}
ViewController.swift
import UIKit
import WebKit

class ViewController: UIViewController {
    var webView: WKWebView!
    override func viewDidLoad() {
        super.viewDidLoad()

        webView = WKWebView(frame: view.frame)

        view.addSubview(webView)

        // MARK: HTML
        /// HTMLのファイルURLを取得する
        guard let html = Bundle.main.url(forResource: "index", withExtension: "html")  else { return }
        /// ファイルURLからファイルの内容をStringで取得
        guard let htmlString = try? String(contentsOf: html) else { return }

        // MARK: CSS
        /// CSSのファイルURLを取得する
        guard let css = Bundle.main.url(forResource: "style", withExtension: "css")  else { return }

        // MARK: 読み込み
        webView.loadHTMLString(htmlString, baseURL: css)

    }

}
❌ HTML ✅ HTML ✅ HTML
❌ CSS ❌ CSS ✅ CSS
simulator_screenshot_46B22246-22AD-412C-9105-D7D7C035B407.png simulator_screenshot_387B14DD-8747-4B23-8726-07E4BD908DDA.png simulator_screenshot_D0F6AA31-9514-4F93-9965-9612CF73D573.png

おわり

WKWebViewでローカルファイルを表示したのは初めてだったのでまとめてみました。

10
5
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
10
5