はじめに
今回はローカルにあるindex.html
とstyle.css
をWKWebViewで読み込む方法を紹介します。
実装
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 |
![]() |
![]() |
![]() |
おわり
WKWebViewでローカルファイルを表示したのは初めてだったのでまとめてみました。