Table of Contents
Swift でブラウザを作るには WKWebView を使用します。
今回は、自分で用意したローカルのHTMLファイルを表示するだけの簡単なブラウザを WKWebView で作る例を紹介します。
サンプルソースコード
Xcodeで新規プロジェクトを「Single View Application」のテンプレートで作成し、ViewController.swift を以下のように書き換えてください。
import UIKit
import WebKit // ブラウザ(WKWebView)に必要
class ViewController: UIViewController {
let statusBarHeight = UIApplication.shared.statusBarFrame.height
override func viewDidLoad() {
super.viewDidLoad()
// ブラウザを起動するボタン
let button = UIButton(type: .system)
button.setTitle("Show Browser", for: .normal)
button.addTarget(self, action: #selector(showBrowser), for: .touchUpInside)
button.sizeToFit()
button.center = self.view.center
self.view.addSubview(button)
}
func showBrowser() {
// サイズを指定してブラウザ作成
let webView = WKWebView(frame: CGRect(x: 0, y: statusBarHeight, width: self.view.frame.width, height: self.view.frame.height - statusBarHeight))
// ローカルのHTMLを読み込む
if let htmlData = Bundle.main.path(forResource: "index", ofType: "html") {
webView.load(URLRequest(url: URL(fileURLWithPath: htmlData)))
self.view.addSubview(webView)
} else {
print("file not found")
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
WKWebView を使用するには WebKit をインポートする必要があります。
コードを書き終えたら、ブラウザで表示するHTMLファイルを用意します。以下のようなHTMLを書いて、ファイル名を index.html としてプロジェクトにインポートしてください。
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<title>Document</title>
</head>
<body>
<h1>テストページ</h1>
<p>ローカルのHTMLを表示</p>
</body>
</html>
ファイルマネージャーでは、次のように index.html が表示された状態にしてください。
サンプルの実行例
「Show Browser」ボタンを押すと、以下のように読み込んだHTMLが表示されます。
以上、SwiftでHTMLファイルを表示するだけの簡単なブラウザの作り方でした。


