swiftでローカルファイルのhtmlファイルをwebviewで表示
webviewでwebサイトを見る場合は
プロジェクト内部に設定したファイルを使用する場合
ViewController
import UIKit class ViewController: UIViewController, UIWebViewDelegate { var webview = UIWebView() //var targetURL = "http://m-shige1979.hatenablog.com/" var targetURL = NSBundle.mainBundle().pathForResource("index", ofType: "html"); override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. // webview 表示 loadAddressURL() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // webview 表示 func loadAddressURL() { self.webview.frame = self.view.bounds self.webview.delegate = self; self.view.addSubview(self.webview) let requestURL = NSURL(string: targetURL!) let req = NSURLRequest(URL: requestURL!) webview.loadRequest(req) } func webView(webView: UIWebView!, shouldStartLoadWithRequest request: NSURLRequest!, navigationType: UIWebViewNavigationType) -> Bool { return true } }
index.html
<!DOCType html> <html> <head> <meta charset="utf8" /> <title>Swift Sample</title> </head> <body> <br /> テスト <br /> <a href="sample2.htm">sample2</a> </body> </html>
sample2.htm
<!DOCType html> <html> <head> <meta charset="utf8" /> <title>Swift Sample</title> </head> <body> <br /> sample2 page <br /> <a href="index.html">index</a> </body> </html>
以下に配置
結果
基本は
var targetURL = NSBundle.mainBundle().pathForResource("index", ofType: "html");
で静的なファイルを指定しているので
ファイル名を変えても対応出来る感じかと思われる
内部にAタグなどでリンクを貼っても参照出来る感じです。
所感
データをHTMLで装飾したい場合はこれの方がいいかもしれない。
毎回textviewとかや画像に文字を打ち込むよりは楽と思う