Swift - 網頁控制元件(UIWebView)載入本地資料,檔案

weixin_34249678發表於2016-11-15

使用UIWebView載入本地資料或資源有如下三種方式:
1,使用 **loadHTMLString **方法載入HTML內容
2,使用 **loadRequest **方法載入本地資源(也可用於載入伺服器資源)
3,先將內容儲存成 **Data **資料,再使用 **load **方法載入

使用樣例
通過 **UISegmentedControl **分別控制網頁控制元件
"網頁HTML",“顯示HTML”“顯示PDF”“loadData顯示PDF”

import UIKit 
class ViewController: UIViewController {
var webView:UIWebView!
 
override func viewDidLoad() {
    super.viewDidLoad()
    let items = ["網頁HTML","顯示HTML", "顯示PDF", "loadData顯示PDF"]
    let segmented = UISegmentedControl(items:items)
    segmented.frame = CGRect(x:50, y:44, width:self.view.frame.size.width - 100, height:40)
    segmented.selectedSegmentIndex = 1
    segmented .addTarget(self, action: #selector(segmentedAction), for: .valueChanged)
     
    self.view.addSubview(segmented)
     
    webView = UIWebView(frame:CGRect(x:0, y:90, width:375, height:600))
     
    self.view .addSubview(webView)
     webView.scrollView.bounces = false // 載入完成防止滑動

    let html = "<h1>歡迎來到:<a href='http://521travel.com'>的墨科技</a></h1>";
    webView.loadHTMLString(html,baseURL:nil)
}
 
func segmentedAction(segmented:UISegmentedControl)
{
    // 獲取選項索引
    if segmented.selectedSegmentIndex == 0
    {
        let url = NSURL(string:"http://www.521Travel.com")
        let request = NSURLRequest(url:url! as URL)
        webView.loadRequest(request as URLRequest)
    }
    else if segmented.selectedSegmentIndex == 1
    {
  //            let html = "<h1>歡迎來到:<a href='http://521travel.com'>的墨科技</a></h1>";
 //            webView.loadHTMLString(html,baseURL:nil)
         
        // 顯示本地Html
        let path = Bundle.main.path(forResource: "Home_newUser", ofType:"html")
        let urlStr = URL.init(fileURLWithPath: path!)
        print(urlStr)
        webView.loadRequest(URLRequest(url:urlStr))
    }
     
    else if segmented.selectedSegmentIndex == 2
    {
        let path = Bundle.main.path(forResource: "Swift", ofType:"pdf")
        let urlStr = URL.init(fileURLWithPath: path!)
        print(urlStr)
        webView.loadRequest(URLRequest(url:urlStr))
    }
    else if segmented.selectedSegmentIndex == 3
    {
        let path = Bundle.main.path(forResource: "Swift", ofType:"pdf")
        let urlStr = URL.init(fileURLWithPath: path!)
        let data = try! Data(contentsOf: urlStr)
        webView.load(data, mimeType: "application/pdf", textEncodingName: "utf-8",
                     baseURL: NSURL() as URL)
    }
}

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

}

點選下載Demo

相關文章