LoginSignup
63
62

More than 5 years have passed since last update.

SwiftでUiWebViewを使ってアプリ内ローカルHTMLを表示する。

Posted at

Webサイトを表示させるときにはUiWebViewを使うのは一般的だと思うのですが、アプリ内にHTMLファイルを設置して、それを参照するやり方が分からなかったので調べましたメモです。

SwiftでWebViewを利用する

Web上のページを表示させる場合

まずは普通にWebサイトを表示してみます。 targetURLにhttp://〜のurlを書きます。

//
//  ViewController.swift
//  sblig_gps
//
//  Created by 菅原 遼介 on 2014/12/04.
//  Copyright (c) 2014年 n0bisuke. All rights reserved.
//

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var uiwebview: UIWebView!
    var targetURL = "http://liginc.co.jp"

    override func viewDidLoad() {
        super.viewDidLoad()
        loadAddressURL()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    func loadAddressURL() {
        let requestURL = NSURL(string: targetURL)
        let req = NSURLRequest(URL: requestURL)
        uiwebview.loadRequest(req)
    }


}

ローカルhtmlファイルを参照する場合

アプリ内のViewController.swiftと同階層のindex.htmlを参照する場合

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

と書きます。

//
//  ViewController.swift
//  sblig_gps
//
//  Created by 菅原 遼介 on 2014/12/04.
//  Copyright (c) 2014年 n0bisuke. All rights reserved.
//

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var uiwebview: UIWebView!
    var targetURL = NSBundle.mainBundle().pathForResource("index", ofType: "html");

    override func viewDidLoad() {
        super.viewDidLoad()
        loadAddressURL()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    func loadAddressURL() {
        let requestURL = NSURL(string: targetURL!)
        let req = NSURLRequest(URL: requestURL)
        uiwebview.loadRequest(req)
    }


}


63
62
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
63
62