m_shige1979のときどきITブログ

プログラムの勉強をしながら学習したことや経験したことをぼそぼそと書いていきます

Github(変なおっさんの顔でるので気をつけてね)

https://github.com/mshige1979

swiftでローカルファイルのhtmlファイルをwebviewで表示

androidの勉強をしているけど

スマホアプリってどっちも同じでしょ」みたいなこといわれるとなんかあれ何でswiftでiphneアプリの勉強もしているこのごろ

webviewでwebサイトを見る場合は


swiftの学習(webviewを使用) - m_shige1979のささやかな抵抗と欲望の日々
で対応

プロジェクト内部に設定したファイルを使用する場合

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>

以下に配置

f:id:m_shige1979:20150117113333p:plain

結果

f:id:m_shige1979:20150117091724p:plain
f:id:m_shige1979:20150117091734p:plain

基本は

var targetURL = NSBundle.mainBundle().pathForResource("index", ofType: "html");

で静的なファイルを指定しているので
ファイル名を変えても対応出来る感じかと思われる
内部にAタグなどでリンクを貼っても参照出来る感じです。

所感

データをHTMLで装飾したい場合はこれの方がいいかもしれない。
毎回textviewとかや画像に文字を打ち込むよりは楽と思う