隨說(shuō) : 最近有個(gè)需求,是將公司的一個(gè)內(nèi)網(wǎng)的頁(yè)面嵌套在app中作為一個(gè)模塊.這不是很簡(jiǎn)單的webView請(qǐng)求一下就行了么?其實(shí)內(nèi)里大有乾坤.自己也將思路整理一遍
UIWebView##
UIWebView的基本使用方法 :###
就這樣就已經(jīng)整整個(gè)baidu的頁(yè)面展示到app上
下面我們看一下webView的屬性與方法
UIWebView *webView = [[UIWebView alloc] initWithFrame:[UIScreen mainScreen].bounds];
self.view = webView;
NSURL *url = [NSURL URLWithString:@"https://www.baidu.com"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[webView loadRequest:request];
UIWebView的層級(jí)結(jié)構(gòu) :###
UIWebView的屬性 :###
// 代理屬性 重點(diǎn)需要知道代理方法的使用
@property (nullable, nonatomic, assign) id <UIWebViewDelegate> delegate;
// 這個(gè)是webView內(nèi)部的scrollView 只讀,但是利用這個(gè)屬性,設(shè)置scrollView的代理,就可以控制整個(gè)webView的滾動(dòng)事件
@property(nonatomic, readonly, strong) UIScrollView *scrollView;
// webView的請(qǐng)求,這個(gè)屬性一般在整個(gè)加載完成后才能拿到
@property (nullable, nonatomic, readonly, strong) NSURLRequest *request;
// A Boolean value indicating whether the receiver can move backward. (read-only)
// If YES, able to move backward; otherwise, NO.
// 如果這個(gè)屬性為YES,才能后退
@property (nonatomic, readonly, getter=canGoBack) BOOL canGoBack;
// A Boolean value indicating whether the receiver can move forward. (read-only)
// If YES, able to move forward; otherwise, NO.
// 如果這個(gè)屬性為YES,才能前進(jìn)
@property (nonatomic, readonly, getter=canGoForward) BOOL canGoForward;
// A Boolean value indicating whether the receiver is done loading content. (read-only)
// If YES, the receiver is still loading content; otherwise, NO.
// 這個(gè)屬性很好用,如果為YES證明webView還在加載數(shù)據(jù),所有數(shù)據(jù)加載完畢后,webView就會(huì)為No
@property (nonatomic, readonly, getter=isLoading) BOOL loading;
//A Boolean value determining whether the webpage scales to fit the view and the user can change the scale.
//If YES, the webpage is scaled to fit and the user can zoom in and zoom out. If NO, user zooming is disabled. The default value is NO.
// YES代表網(wǎng)頁(yè)可以縮放,NO代表不可以縮放
@property (nonatomic) BOOL scalesPageToFit;
// 設(shè)置某些數(shù)據(jù)變?yōu)殒溄有问侥担@個(gè)枚舉可以設(shè)置如電話號(hào),地址,郵箱等轉(zhuǎn)化為鏈接
@property (nonatomic) UIDataDetectorTypes dataDetectorTypes NS_AVAILABLE_IOS(3_0);
// iPhone Safari defaults to NO. iPad Safari defaults to YES
// 設(shè)置是否使用內(nèi)聯(lián)播放器播放視頻
@property (nonatomic) BOOL allowsInlineMediaPlayback NS_AVAILABLE_IOS(4_0);
// iPhone and iPad Safari both default 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 NO
// 設(shè)置是否將數(shù)據(jù)加載入內(nèi)存后渲染界面
@property (nonatomic) BOOL suppressesIncrementalRendering NS_AVAILABLE_IOS(6_0);
// default is YES
// 設(shè)置用戶是否能打開(kāi)keyboard交互
@property (nonatomic) BOOL keyboardDisplayRequiresUserAction NS_AVAILABLE_IOS(6_0);
/* IOS7 */ 以后的新特性
// 這個(gè)屬性用來(lái)設(shè)置一種模式日杈,當(dāng)網(wǎng)頁(yè)的大小超出view時(shí),將網(wǎng)頁(yè)以翻頁(yè)的效果展示,枚舉如下:
@property (nonatomic) UIWebPaginationMode paginationMode NS_AVAILABLE_IOS(7_0);
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è)
};
// This property determines whether certain CSS properties regarding column- and page-breaking are honored or ignored.
// 這個(gè)屬性決定CSS的屬性分頁(yè)是可用還是忽略蠢笋。默認(rèn)是UIWebPaginationBreakingModePage
@property (nonatomic) UIWebPaginationBreakingMode paginationBreakingMode NS_AVAILABLE_IOS(7_0);
// 設(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);
還有一些屬性請(qǐng)?jiān)敿?xì)翻蘋果文檔
UIWebView的代理方法 :###
UIWebView的代理方法是用的最多的方法,并且一般來(lái)說(shuō),相對(duì)Web頁(yè)面作處理都在這相應(yīng)的4個(gè)方法中
分別解釋一下方法的調(diào)用情況
// Sent before a web view begins loading a frame.請(qǐng)求發(fā)送前都會(huì)調(diào)用該方法,返回NO則不處理這個(gè)請(qǐng)求
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType;
// Sent after a web view starts loading a frame. 請(qǐng)求發(fā)送之后開(kāi)始接收響應(yīng)之前會(huì)調(diào)用這個(gè)方法
- (void)webViewDidStartLoad:(UIWebView *)webView;
// Sent after a web view finishes loading a frame. 請(qǐng)求發(fā)送之后,并且服務(wù)器已經(jīng)返回響應(yīng)之后調(diào)用該方法
- (void)webViewDidFinishLoad:(UIWebView *)webView;
// Sent if a web view failed to load a frame. 網(wǎng)頁(yè)請(qǐng)求失敗則會(huì)調(diào)用該方法
- (void)webView:(UIWebView *)webView didFailLoadWithError:(nullable NSError *)error;
UIWebView的對(duì)象方法###
// 加載Data數(shù)據(jù)創(chuàng)建一個(gè)webView
- (void)loadData:(NSData *)data MIMEType:(NSString *)MIMEType textEncodingName:(NSString *)encodingName baseURL:(NSURL *)baseURL
// 加載本地HTML創(chuàng)建一個(gè)webView
- (void)loadHTMLString:(NSString *)string baseURL:(NSURL *)baseURL
// 加載一個(gè)請(qǐng)求創(chuàng)建一個(gè)webView
- (void)loadRequest:(NSURLRequest *)request
// 刷新網(wǎng)頁(yè)
- (void)reload;
// 停止網(wǎng)頁(yè)加載內(nèi)容
- (void)stopLoading;
// 后退
- (void)goBack;
// 前進(jìn)
- (void)goForward;
// 執(zhí)行JS方法
- (NSString *)stringByEvaluatingJavaScriptFromString:(NSString *)script
WKWebView##
WKWebView的簡(jiǎn)介 :###
從文檔中可以看到,這個(gè)是IOS8之后新增的一個(gè)類,也是蘋果推崇的一個(gè)新的類
WKWebView的基本使用方法 :###
其實(shí)和UIWebView的用法沒(méi)什么區(qū)別
但是WKWebView相對(duì)于UIWebView強(qiáng)大了很多,內(nèi)存的消耗相對(duì)少了鳞陨,所提供的接口也豐富了昨寞。
推薦使用
多了一部操作就是需要包含webkit框架
@import webkit
WKWebView *webView = [[WKWebView alloc] initWithFrame:[UIScreen mainScreen].bounds];
self.view = webView;
NSURL *url = [NSURL URLWithString:@"https://www.baidu.com"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[webView loadRequest:request];
WKWebView的屬性 :###
// UIWebView 中會(huì)自動(dòng)保存Cookie瞻惋,如果登錄了一次下次再次進(jìn)入的時(shí)候,會(huì)記住登錄狀態(tài)
// 在WKWebView中,新增一個(gè)configuration屬性, configuration 讓W(xué)KWebView知道登錄狀態(tài)援岩,
// configuration 可以通過(guò)已有的Cookie進(jìn)行設(shè)置歼狼,也可以通過(guò)保存上一次的configuration進(jìn)行設(shè)置
// WKWebViewConfiguration類中也有一些相應(yīng)的屬性
@property (nonatomic, readonly, copy) WKWebViewConfiguration *configuration;
// The methods of the WKNavigationDelegate protocol help you track the progress of the web site's main frame navigations and decide load policy for main frame and subframe navigations.
// WKWebView中,加入了網(wǎng)站導(dǎo)航的概念,這個(gè)對(duì)象決定主框架導(dǎo)航加載方法協(xié)議。
@property (nullable, nonatomic, weak) id <WKNavigationDelegate> navigationDelegate;
// The WKUIDelegate class provides methods for presenting native user interface
elements on behalf of a webpage.
// WKWebView中,加入了網(wǎng)站窗口的概念,這個(gè)對(duì)象決了webView窗口的一些方法協(xié)議享怀。
@property (nullable, nonatomic, weak) id <WKUIDelegate> UIDelegate;
A WKBackForwardList object is a list of webpages previously visited in a web view that can be reached by going back or forward.
// WKWebView中,加入了網(wǎng)站列表的概念,這個(gè)WEBBackForwardList對(duì)象是以前在Web視圖訪問(wèn)的網(wǎng)頁(yè)羽峰,可以通過(guò)去后退或前進(jìn)
@property (nonatomic, readonly, strong) WKBackForwardList *backForwardList;
還有很多方法,同樣可以查文檔看到
WKWebView的代理方法 :###
有一些方法和UIWebView是基本一直的,但是因?yàn)榉祷亓薾avigation,所能用到的屬性多了很多,另外多了一些方法,將請(qǐng)求與相應(yīng)的整個(gè)過(guò)程
- (void)webViewWebContentProcessDidTerminate:(WKWebView *)webView{
NSLog(@"webViewWebContentProcessDidTerminate: 當(dāng)Web視圖的網(wǎng)頁(yè)內(nèi)容被終止時(shí)調(diào)用。");
}
- (void)webView:(WKWebView *)webView didFinishNavigation:(null_unspecified WKNavigation *)navigation
{
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
NSLog(@"webView:didFinishNavigation: 響應(yīng)渲染完成后調(diào)用該方法 webView : %@ -- navigation : %@ \n\n",webView,navigation);
}
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(null_unspecified WKNavigation *)navigation
{
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
NSLog(@"webView:didStartProvisionalNavigation: 開(kāi)始請(qǐng)求 \n\n");
}
- (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation {
NSLog(@"webView:didCommitNavigation: 響應(yīng)的內(nèi)容到達(dá)主頁(yè)面的時(shí)候響應(yīng),剛準(zhǔn)備開(kāi)始渲染頁(yè)面應(yīng)用 \n\n");
}
// error
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation withError:(NSError *)error {
// 類似 UIWebView 的- webView:didFailLoadWithError:
NSLog(@"webView:didFailProvisionalNavigation:withError: 啟動(dòng)時(shí)加載數(shù)據(jù)發(fā)生錯(cuò)誤就會(huì)調(diào)用這個(gè)方法添瓷。 \n\n");
}
- (void)webView:(WKWebView *)webView didFailNavigation:(WKNavigation *)navigation withError:(NSError *)error{
NSLog(@"webView:didFailNavigation: 當(dāng)一個(gè)正在提交的頁(yè)面在跳轉(zhuǎn)過(guò)程中出現(xiàn)錯(cuò)誤時(shí)調(diào)用這個(gè)方法梅屉。 \n\n");
}
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler{
NSLog(@"請(qǐng)求前會(huì)先進(jìn)入這個(gè)方法 webView:decidePolicyForNavigationActiondecisionHandler: %@ \n\n ",navigationAction.request);
decisionHandler(WKNavigationActionPolicyAllow);
}
- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler{
NSLog(@"返回響應(yīng)前先會(huì)調(diào)用這個(gè)方法 并且已經(jīng)能接收到響應(yīng)webView:decidePolicyForNavigationResponse:decisionHandler: Response?%@ \n\n",navigationResponse.response);
decisionHandler(WKNavigationResponsePolicyAllow);
}
- (void)webView:(WKWebView *)webView didReceiveServerRedirectForProvisionalNavigation:(WKNavigation *)navigation{
NSLog(@"webView:didReceiveServerRedirectForProvisionalNavigation: 重定向的時(shí)候就會(huì)調(diào)用 \n\n");
}
WKWebView的對(duì)象方法 :###
這些方法,基本上和UIWebView中的使用用法是一致的,所以
// 這是加載網(wǎng)頁(yè)最常用的一種方式,通過(guò)一個(gè)網(wǎng)頁(yè)URL來(lái)加載一個(gè)WKWebView鳞贷,這個(gè)URL可以是遠(yuǎn)程的也可以是本地的坯汤,例如我加載百度的主頁(yè)
- (nullable WKNavigation *)loadRequest:(NSURLRequest *)request;
// 根據(jù)一個(gè)文件,加載一個(gè)WKWebView
- (nullable WKNavigation *)loadFileURL:(NSURL *)URL allowingReadAccessToURL:(NSURL *)readAccessURL NS_AVAILABLE(10_11, 9_0);
// 這個(gè)方法需要將html文件讀取為字符串從而加載為WKWebView,其中baseURL是我們自己設(shè)置的一個(gè)路徑搀愧,用于尋找html文件中引用的圖片等素材惰聂。
- (nullable WKNavigation *)loadHTMLString:(NSString *)string baseURL:(nullable NSURL *)baseURL;
// 這個(gè)方式使用的比較少,但也更加自由妈橄,其中data是文件數(shù)據(jù)庶近,MIMEType是文件類型翁脆,characterEncodingName是編碼類型眷蚓,baseURL是素材資源路徑
- (nullable WKNavigation *)loadData:(NSData *)data MIMEType:(NSString *)MIMEType characterEncodingName:(NSString *)characterEncodingName baseURL:(NSURL *)baseURL NS_AVAILABLE(10_11, 9_0);
基本使用##
下面會(huì)總結(jié)一些我在開(kāi)發(fā)過(guò)程中遇到的坑,和解決問(wèn)題的一些思路,不過(guò)在此之前我發(fā)現(xiàn),如果要webView玩得好,有以下幾點(diǎn)的只是也需要掌握好,因?yàn)槲艺J(rèn)為在H5崛起的今天,源生App和H5的交互之間會(huì)產(chǎn)生比較大改變,而且源生與H5之間的混編,越來(lái)越被重視.所以 :
- 源生技術(shù),特別是有關(guān)于webView這一塊的API要非常熟練,
- js語(yǔ)法, js的語(yǔ)法需要熟練,特別是操作document的幾個(gè)常用js,標(biāo)簽需要用得滾瓜爛熟.
- 要非常了解網(wǎng)絡(luò)請(qǐng)求 - 響應(yīng)的機(jī)制,理解請(qǐng)求頭,響應(yīng)頭,等等.HTTP的整套協(xié)議
需求一 : 展示一個(gè)網(wǎng)頁(yè),但是需要隱藏一部分頁(yè)面###
首先看看百度的頁(yè)面,這是用Chrome瀏覽器打開(kāi)的開(kāi)發(fā)者模式
基本界面組成如下,基本使用用法請(qǐng)?jiān)斍榘俣?這里不作介紹
假設(shè)現(xiàn)在想將這個(gè)Logo由網(wǎng)頁(yè)開(kāi)始加載就去掉
百度的logo就是一個(gè)div套著一個(gè)image標(biāo)簽
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
// 在HTML標(biāo)簽都加載完成后,開(kāi)始處理HTML標(biāo)簽,調(diào)用JS,操作document
[webView stringByEvaluatingJavaScriptFromString:@"document.getElementById('plus-card').remove();"];
}
就這樣, logo標(biāo)簽就被去掉了,思路就是等HTML加載完成后,操作JS從而操作document標(biāo)簽從而改變整個(gè)html頁(yè)面的應(yīng)用,下圖是去掉整個(gè)Body主題內(nèi)容后的結(jié)果
另外還可以將一段函數(shù)封裝到里面,執(zhí)行函數(shù),原理是通過(guò)stringByEvaluatingJavaScriptFromString將JS函數(shù)寫進(jìn)head標(biāo)簽中,然后再調(diào)用該函數(shù)
// 自定義editMyLogo函數(shù)
[webView stringByEvaluatingJavaScriptFromString:@"var script = document.createElement('script');"
"script.type = 'text/javascript';"
"script.text = \"function editMyLogo() { "
"var logo = document.getElementById('logo');"
"logo.innerHTML= logo.innerHTML + '這是我自己定義的名字';"
"var imglist = logo.getElementsByTagName('IMG');"
"for (i=0 ; i < imglist.length ; i++ ){"
"imglist[i].src = 'http://pic.to8to.com/attch/day_160218/20160218_d968438a2434b62ba59dH7q5KEzTS6OH.png';"
"}"
"}\";"
"document.getElementsByTagName('head')[0].appendChild(script);"];
// 執(zhí)行editMyLogo函數(shù)
[webView stringByEvaluatingJavaScriptFromString:@"editMyLogo();"];
效果如下 :
有幾點(diǎn)問(wèn)題,這種操作是在webViewDidFinishLoad方法下進(jìn)行的,webViewDidFinishLoad方法是webView的document已經(jīng)渲染好后,再去處理這個(gè)這個(gè)頁(yè)面.
- 你會(huì)發(fā)現(xiàn)有時(shí)候會(huì)出現(xiàn)一些閃屏現(xiàn)象,原因是渲染過(guò)后,內(nèi)部處理JS代碼后,頁(yè)面會(huì)再渲染一次
- 資源浪費(fèi),假設(shè)這邊的需求只需要顯示10%的內(nèi)容,卻要加載100%的內(nèi)容,不過(guò)這一方面還需要網(wǎng)頁(yè)端作出很好的適配
- 某些時(shí)候,JS會(huì)失效,不知道什么原因,有些時(shí)候自定義加載的JS的方法并沒(méi)有執(zhí)行到.等于內(nèi)容并沒(méi)有屏蔽
- 等等..
需求二 : 怎樣處理403,404的情況 ?###
@property (nonatomic, assign) BOOL isPost; // 定義一個(gè)變量
// 每一個(gè)請(qǐng)求開(kāi)始發(fā)送前都會(huì)調(diào)用這個(gè)方法
// 1, 定義一個(gè)全局變量currentRequest,用作保存當(dāng)前的請(qǐng)求
// 2, 將請(qǐng)求轉(zhuǎn)換成data,然后處理data再將data作為請(qǐng)求數(shù)據(jù)再次請(qǐng)求
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
if (!_isPost) {
NSHTTPURLResponse *response = nil;
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
if (response.statusCode == 404) {
// 這里處理 404 代碼
} else if (response.statusCode == 403) {
// 這里處理 403 代碼
} else {
_isPost = true;
[webView loadData:data MIMEType:@"text/html" textEncodingName:@"NSUTF8StringEncoding" baseURL:[request URL]];
}
return NO;
}else{
NSLog(@"\n\n shouldStartLoadWithRequest請(qǐng)求準(zhǔn)備 -- %@ \n\n ",request);
_isPost = NO;
return YES;
}
}
需求一 : 進(jìn)一步改進(jìn)###
在處理HTML這里,將你想隱藏的頁(yè)面,加上 display:none 屬性,
或者,將整段HTML標(biāo)簽去掉.
系列的其他整理
[IOS混合編程 - UIWebView 與 WKWebView . 基本使用 (一)][1]
[IOS混合編程 - Http for IOS (二)][2]
[IOS混合編程 - NSURLProtocol 的使用 (三)][3]
[1]: http://www.reibang.com/p/b3e7fa514ab7
[2]: http://www.reibang.com/p/a6830a9287d6
[3]: http://www.reibang.com/p/ec5d6c204e17