微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Swift - 网页控件UIWebView加载本地数据,文件

使用UIWebView加载本地数据或资源有如下三种方式:
1,使用loadHTMLString方法加载HTML内容
2,使用loadRequest方法加载本地资源(也可用于加载服务器资源)
3,先将内容保存成NSData数据,再使用loadData方法加载

示例代码如下(通过UISegmentedControl分别控制网页控件“显示HTML”“显示PDF”“loadData显示PDF”):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
import UIKit
class ViewController : UIViewController {
@IBOutlet var webview: UIWebView !
loadtype: UISegmentedControl !
override func viewDidLoad() {
super .viewDidLoad()
//认选中分段控件的第一项
loadtype.selectedSegmentIndex = 0
typeChanged(loadtype)
}
@IBAction typeChanged(sender: UISegmentedControl )
{
let index = sender.selectedSegmentIndex
print (index)
switch index
{
case 0: //在 UIWebView 中显示 HTML 内容
html = "<h1>欢迎来到:<a href='http://hangge.com'>航歌</a></h1>" ;
webview.loadHTMLString(html,baseURL: nil )
1: //在 UIWebView 中显示 PDF
path = NSBundle .mainBundle().pathForResource( "test1" ,ofType: "pdf" )
urlStr = NSURL .fileURLWithPath(path!);
(urlStr)
webview.loadRequest( NSURLRequest ( URL :urlStr));
2: //在 UIWebView 中显示 PDF,但是是通过 loadData 方式加载
path = NSBundle )
.fileURLWithPath(path!);
data = NSData (contentsOfURL:urlStr);
webview.loadData(data!, MIMEType : "application/pdf" ottom:auto!important; float:none!important; height:auto!important; left:auto!important; line-height:1.5em!important; margin:0px!important; overflow:visible!important; padding:1px 0px!important; position:static!important; right:auto!important; top:auto!important; vertical-align:baseline!important; width:auto!important; font-family:Consolas,
textEncodingName: "utf-8" ottom:auto!important; float:none!important; height:auto!important; left:auto!important; line-height:1.5em!important; margin:0px!important; overflow:visible!important; padding:1px 0px!important; position:static!important; right:auto!important; top:auto!important; vertical-align:baseline!important; width:auto!important; font-family:Consolas,baseURL: NSURL ());
default :
( "是不是出错了?" )
}
}
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐