前言
好久沒(méi)有寫簡(jiǎn)書(shū)了舵抹,突然感覺(jué)有點(diǎn)生疏肪虎。最近一直在思考人生,不知道何去何從惧蛹。總之刑枝,就是頭疼……好了香嗓,廢話不多說(shuō),今天來(lái)記錄一下UIWebView装畅,隨著H5的流行靠娱,UIWebView也火了起來(lái),對(duì)于平時(shí)不怎么使用UIWebView的我來(lái)說(shuō)掠兄,真該學(xué)習(xí)一下了像云。(正好,最近自己也在學(xué)習(xí)H5),下來(lái)我給大家介紹一下OC與JS的交互蚂夕,但是前提是迅诬,你得熟悉UIWebView。
UIWebView基本用法
UIWebView的基本用法都是一些很簡(jiǎn)單的東西婿牍,相信只要你會(huì)用UIButton侈贷,一般就能搞定UIWebView。
UIWebView加載
UIWebView提供了三種加載html界面的方法:
/**通過(guò)NSURLRequest去加載html界面**/
- (void)loadRequest:(NSURLRequest *)request;
/**加載html格式的字符串等脂,其中的baseUrl下面會(huì)介紹**/
- (void)loadHTMLString:(NSString *)string baseURL:(nullable NSURL *)baseURL;
/**這種方式表示沒(méi)見(jiàn)到過(guò)俏蛮,我也不知道是什么,有興趣的可以自己去查查**/
- (void)loadData:(NSData *)data MIMEType:(NSString *)MIMEType textEncodingName:(NSString *)textEncodingName baseURL:(NSURL *)baseURL;(*很少用*)
示例如下:
(void)loadRequest:(NSURLRequest *)request方法即可以去通過(guò)網(wǎng)絡(luò)連接加載html資源上遥,也可以去加載本地的html資源搏屑。
加載網(wǎng)絡(luò)地址
NSURLRequest request =[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.superqq.com"]];
[self.view addSubview:webView];
[webView loadRequest:request];
加載本地Html
NSString path = [[NSBundle mainBundle] pathForResource:@"swift" ofType:@"html"];
NSURL url = [NSURL fileURLWithPath:path];//創(chuàng)建URL
NSURLRequest request = [NSURLRequest requestWithURL:url];//創(chuàng)建NSURLRequest
[webView loadRequest:request];//加載-
(void)loadHTMLString:(NSString *)string baseURL:(nullable NSURL *)baseURL方法一般用來(lái)加載本地的html界面。
NSString *localHTMLPageName = @"myPage";
NSString *path = [[NSBundle mainBundle] pathForResource:localHTMLPageName ofType:@"html"];// 從html文件中讀取html字符串 NSFileHandle *readHandle = [NSFileHandle fileHandleForReadingAtPath:path]; NSString *htmlString = [[NSString alloc] initWithData: [readHandle readDataToEndOfFile] encoding:NSUTF8StringEncoding]; // 或使用 // NSString *htmlString = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:NULL]; // baseURL用來(lái)確定htmlString的基準(zhǔn)地址粉楚, // 相當(dāng)于HTML的<base>標(biāo)簽的作用辣恋,定義頁(yè)面中所有鏈接的默認(rèn)地址。 [webView loadHTMLString:htmlString baseURL:[[NSBundle mainBundle] bundleURL]];
注意:baseURLbaseURL用來(lái)確定htmlString的基準(zhǔn)地址,相當(dāng)于HTML的<base>標(biāo)簽的作用抑党,定義頁(yè)面中所有鏈接的默認(rèn)地址包警。具體查看W3C上的base標(biāo)簽。
baseURL是HTML字符串中引用到資源的查找路徑底靠,當(dāng)HTML中沒(méi)有引用外部資源時(shí)害晦,可以指定為nil;若引用了外部資源(外部資源:除了html代碼以外暑中,界面中所有的圖片壹瘟,鏈接都屬于外部資源),一般情況下使用mainBundle的路徑即可鳄逾。在實(shí)際操作中稻轨,常常會(huì)出現(xiàn)「文本顯示正常,圖片無(wú)法顯示」等情況雕凹,若HTML文本中引用外部資源都是使用相對(duì)路徑殴俱,則出現(xiàn)這種問(wèn)題的原因一般都是baseURL參數(shù)錯(cuò)誤。
UIWebView的一些常用屬性和方法(這部分東西轉(zhuǎn)載自:http://www.reibang.com/p/fbdb09b6b564)
**webView的代理**
@property (nullable, nonatomic, assign) id <UIWebViewDelegate> delegate;
**內(nèi)置的scrollView**
@property (nonatomic, readonly, strong) UIScrollView
*scrollView NS_AVAILABLE_IOS(5_0);
**URL請(qǐng)求**
@property (nullable, nonatomic, readonly, strong) NSURLRequest *request;
**是否縮放到適合屏幕大小**
@property (nonatomic) BOOL scalesPageToFit;
**執(zhí)行javaScript操作**
- (nullable NSString *)stringByEvaluatingJavaScriptFromString:(NSString *)script;
加載屬性
- (void)reload; //重新加載數(shù)據(jù)
- (void)stopLoading; //停止加載數(shù)據(jù)
@property (nonatomic, readonly, getter=isLoading) BOOL loading; //是否正在加載
- (void)goBack; //返回上一級(jí)
- (void)goForward; //跳轉(zhuǎn)下一級(jí)
@property (nonatomic, readonly, getter=canGoBack) BOOL canGoBack; //能否返回上一級(jí)
@property (nonatomic, readonly, getter=canGoForward) BOOL canGoForward; //能否跳轉(zhuǎn)下一級(jí)
多媒體屬性
//YES枚抵,自動(dòng)檢測(cè)網(wǎng)頁(yè)上的電話號(hào)碼线欲,單擊可以撥打
@property (nonatomic) BOOL detectsPhoneNumbers NS_DEPRECATED_IOS(2_0, 3_0);
//設(shè)置某些數(shù)據(jù)變?yōu)殒溄有问剑@個(gè)枚舉可以設(shè)置如電話號(hào)汽摹,地址李丰,郵箱等轉(zhuǎn)化為鏈接
@property (nonatomic) UIDataDetectorTypes dataDetectorTypes NS_AVAILABLE_IOS(3_0);
//設(shè)置是否使用內(nèi)聯(lián)播放器播放視頻
@property (nonatomic) BOOL allowsInlineMediaPlayback NS_AVAILABLE_IOS(4_0); // iPhone Safari defaults to NO. iPad Safari defaults to YES
//設(shè)置視頻是否自動(dòng)播放
@property (nonatomic) BOOL mediaPlaybackRequiresUserAction NS_AVAILABLE_IOS(4_0); // iPhone and iPad Safari both default to YES
//設(shè)置音頻播放是否支持ari play功能
@property (nonatomic) BOOL mediaPlaybackAllowsAirPlay NS_AVAILABLE_IOS(5_0); // iPhone and iPad Safari both default to YES
//設(shè)置是否將數(shù)據(jù)加載如內(nèi)存后渲染界面
@property (nonatomic) BOOL suppressesIncrementalRendering NS_AVAILABLE_IOS(6_0); // iPhone and iPad Safari both default to NO
//設(shè)置用戶交互模式
@property (nonatomic) BOOL keyboardDisplayRequiresUserAction NS_AVAILABLE_IOS(6_0);
iOS7.0 新特性
@property (nonatomic) UIWebPaginationMode paginationMode NS_AVAILABLE_IOS(7_0);
這個(gè)屬性用來(lái)設(shè)置一種模式,當(dāng)網(wǎng)頁(yè)的大小超出view時(shí)逼泣,將網(wǎng)頁(yè)以翻頁(yè)的效果展示趴泌,枚舉如下:
typedef NS_ENUM(NSInteger, UIWebPaginationMode)
{
UIWebPaginationModeUnpaginated, //不使用翻頁(yè)效果
UIWebPaginationModeLeftToRight, //將網(wǎng)頁(yè)超出部分分頁(yè),從左向右進(jìn)行翻頁(yè)
UIWebPaginationModeTopToBottom, //將網(wǎng)頁(yè)超出部分分頁(yè)拉庶,從上向下進(jìn)行翻頁(yè)
UIWebPaginationModeBottomToTop, //將網(wǎng)頁(yè)超出部分分頁(yè)嗜憔,從下向上進(jìn)行翻頁(yè)
UIWebPaginationModeRightToLeft //將網(wǎng)頁(yè)超出部分分頁(yè),從右向左進(jìn)行翻頁(yè)
} __TVOS_PROHIBITED;
//設(shè)置每一頁(yè)的長(zhǎng)度
@property (nonatomic) CGFloat pageLength NS_AVAILABLE_IOS(7_0);
//設(shè)置每一頁(yè)的間距
@property (nonatomic) CGFloat gapBetweenPages NS_AVAILABLE_IOS(7_0);
//獲取分頁(yè)數(shù)
@property (nonatomic, readonly) NSUInteger pageCount NS_AVAILABLE_IOS(7_0);
@property (nonatomic) UIWebPaginationBreakingMode paginationBreakingMode NS_AVAILABLE_IOS(7_0);
typedef NS_ENUM(NSInteger, UIWebPaginationBreakingMode)
{
UIWebPaginationBreakingModePage,
UIWebPaginationBreakingModeColumn
} __TVOS_PROHIBITED;
iOS9.0新特性
//是否允許畫(huà)中畫(huà)播放
@property (nonatomic) BOOL allowsPictureInPictureMediaPlayback NS_AVAILABLE_IOS(9_0);
//A Boolean value that determines whether pressing on a link displays a preview of the destination for the link.
This property is available on devices that support 3D Touch. Default value is NO.
@property (nonatomic) BOOL allowsLinkPreview NS_AVAILABLE_IOS(9_0); //
UIWebView的代理方法
//設(shè)置代理砍的,同時(shí)實(shí)現(xiàn)UIWebViewDelegate
webView.delegate = self;
//代理方法
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
/**返回YES痹筛,進(jìn)行加載。通過(guò)UIWebViewNavigationType可以得到請(qǐng)求發(fā)起的原因
如果為webView添加了delegate對(duì)象并實(shí)現(xiàn)該接口廓鞠,那么在webView加載任何一個(gè)frame之前都會(huì)delegate對(duì)象的該方法帚稠,該方法的返回值用以控制是否允許加載目標(biāo)鏈接頁(yè)面的內(nèi)容,返回YES將直接加載內(nèi)容床佳,NO則反之滋早。并且UIWebViewNavigationType枚舉,定義了頁(yè)面中用戶行為的分類砌们,包括
UIWebViewNavigationTypeLinkClicked杆麸,用戶觸擊了一個(gè)鏈接搁进。
UIWebViewNavigationTypeFormSubmitted,用戶提交了一個(gè)表單昔头。
UIWebViewNavigationTypeBackForward饼问,用戶觸擊前進(jìn)或返回按鈕。
UIWebViewNavigationTypeReload揭斧,用戶觸擊重新加載的按鈕莱革。
UIWebViewNavigationTypeFormResubmitted,用戶重復(fù)提交表單
UIWebViewNavigationTypeOther讹开,發(fā)生其它行為盅视。
*/
return YES;
}
- (void)webViewDidStartLoad:(UIWebView *)webView
{
//開(kāi)始加載,可以加上風(fēng)火輪(也叫菊花)
}
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
//完成加載
}
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
//加載出錯(cuò)
}
禁用頁(yè)面滾動(dòng)彈跳
webView.scrollView.bounces = NO ;
移除滾動(dòng)后的外邊陰影
UIWebView包含一個(gè)scrollView組件旦万,用來(lái)將關(guān)聯(lián)web內(nèi)容實(shí)現(xiàn)滾動(dòng)效果闹击,頁(yè)面滾動(dòng)后的UIWebView的面板周圍會(huì)出現(xiàn)陰影效果,該效果是在四周添加UIImageView實(shí)現(xiàn)的成艘,因此移除這種陰影效果的代碼如下:
UIScrollView *scrollView = webView.scrollView;
for (int i = 0; i < scrollView.subviews.count ; i++) {
UIView *view = [scrollView.subviews objectAtIndex:i];
if ([view isKindOfClass:[UIImageView class]]) {
view.hidden = YES ;
}
}
處理webView展示txt文檔亂碼問(wèn)題
if ([theType isEqualToString:@".txt"])
{
//txt分帶編碼和不帶編碼兩種赏半,帶編碼的如UTF-8格式txt,不帶編碼的如ANSI格式txt
//不帶的狰腌,可以依次嘗試GBK和GB18030編碼
NSString* aStr = [[NSString alloc] initWithData:attachmentData encoding:NSUTF8StringEncoding];
if (!aStr) {
//用GBK進(jìn)行編碼
aStr=[[NSString alloc] initWithData:attachmentData encoding:0x80000632];
}
if (!aStr) {
//用GBK編碼不行,再用GB18030編碼
aStr=[[NSString alloc] initWithData:attachmentData encoding:0x80000631];
}
//通過(guò)html語(yǔ)言進(jìn)行排版
NSString* responseStr = [NSString stringWithFormat:
@"<HTML>"
"<head>"
"<title>Text View</title>"
"</head>"
"<BODY>"
"<pre>" "%@" "/pre>"
"</BODY>"
"</HTML>", aStr];
[attachmentWebView loadHTMLString:responseStr baseURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] bundlePath]]]; return;
}
UIWebView的整個(gè)流程
1除破、 Loading a local PDF file into the web view
- (void)viewDidLoad {
[super viewDidLoad];
//從本地加載
NSString *thePath = [[NSBundle mainBundle] pathForResource:@"iPhone_User_Guide" ofType:@"pdf"];
if (thePath) {
NSData *pdfData = [NSData dataWithContentsOfFile:thePath];
[(UIWebView *)self.view loadData:pdfData MIMEType:@"application/pdf" textEncodingName:@"utf-8" baseURL:nil];
}
//從網(wǎng)絡(luò)加載
[self.myWebView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.apple.com/"]]];}
2、The web-view delegate managing network loading
- (void)webViewDidStartLoad:(UIWebView *)webView{
// starting the load, show the activity indicator in the status bar
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
}
- (void)webViewDidFinishLoad:(UIWebView *)webView{
// finished loading, hide the activity indicator in the status bar
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error{
// load error, hide the activity indicator in the status bar
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
// report the error inside the webview
NSString* errorString = [NSString stringWithFormat: @"<html><center><font size=+5 color='red'>An error occurred:<br>%@</font></center></html>", error.localizedDescription];
[self.myWebView loadHTMLString:errorString baseURL:nil];}
3琼腔、Stopping a load request when the web view is to disappear
- (void)viewWillDisappear:(BOOL)animated{ if ( [self.myWebView loading] ) {
[self.myWebView stopLoading]; } self.myWebView.delegate = nil;
// disconnect the delegate as the webview is hidden
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}
/************/引用自蘋果官方文檔(displaying web content)
參考博客:
http://www.reibang.com/p/fbdb09b6b564
http://zhangbuhuai.com/2015/06/16/UIWebView-loading-local-html/
http://my.oschina.net/u/557242/blog/70836
https://m.oschina.net/blog/147507
歡迎關(guān)注我的個(gè)人微信公眾號(hào),免費(fèi)送計(jì)算機(jī)各種最新視頻資源踱葛!你想象不到的精彩丹莲!