使用UIWebView加载本地数据或资源有如下三种方式:
- 使用 loadHTMLString 方法加载HTML内容
- 使用 loadRequest 方法加载本地资源(也可用于加载服务器资源)
- 先将内容保存成 Data 数据,再使用 load 方法加载
Demo说明:
通过 UISegmentedControl 分别控制网页控件“显示HTML”“显示PDF”“loadData显示PDF”
代码:
import UIKit
class ViewController: UIViewController {
var segmentedControl : UISegmentedControl!
var webView : UIWebView!
override func viewDidLoad() {
super.viewDidLoad()
//创建分段控制器
let items = ["显示HTML", "显示PDF", "load显示PDF"]
segmentedControl = UISegmentedControl(items: items)
segmentedControl.frame = CGRect(x: 5, y: 25, width: view.bounds.width - 10, height: 28)
segmentedControl.tintColor = UIColor.blue
segmentedControl.addTarget(self, action: #selector(segmentChanged(segment:)), for: .valueChanged)
view.addSubview(segmentedControl)
//创建网页控件
let webViewY = segmentedControl.frame.maxY + 20
let webViewH = view.bounds.height - webViewY
webView = UIWebView(frame: CGRect(x: 5, y: webViewY, width: view.bounds.width - 10, height: webViewH))
view.addSubview(webView)
segmentedControl.selectedSegmentIndex = 0
segmentChanged(segment: segmentedControl)
}
@objc func segmentChanged(segment:UISegmentedControl) {
let index = segment.selectedSegmentIndex
switch index {
case 0: //在 UIWebView 中显示 HTML 内容
let html = "<h1>微信公众号:<a href='http://jianshu.com'>解码</a></h1>"
webView.loadHTMLString(html, baseURL: nil)
case 1: //在 UIWebView 中显示 PDF
let path = Bundle.main.path(forResource: "webpdf", ofType: "pdf")
let url = URL.init(fileURLWithPath: path!)
webView.loadRequest(URLRequest(url: url))
case 2: //在 UIWebView 中显示 PDF, 但是是通过 loadData 方式加载
let path = Bundle.main.path(forResource: "test1", ofType: "pdf")
let url = URL.init(fileURLWithPath: path!)
let data = try! Data(contentsOf: url)
webView.load(data, mimeType: "application/pdf", textEncodingName: "utf-8", baseURL: NSURL() as URL)
default:
print("可能出错了!")
}
}
}
网友评论