WKWebView
看看WKWebView的頭文件聲明:
WKWebView
// webview 配置,具體看下面
@property(nonatomic,readonly,copy)WKWebViewConfiguration*configuration;
// 導航代理
@property(nullable,nonatomic,weak)idnavigationDelegate;
// 用戶交互代理
@property(nullable,nonatomic,weak)idUIDelegate;
// 頁面前進、后退列表
@property(nonatomic,readonly,strong)WKBackForwardList*backForwardList;
// 默認構造器
-(instancetype)initWithFrame:(CGRect)frameconfiguration:(WKWebViewConfiguration*)configurationNS_DESIGNATED_INITIALIZER;
// 已不再使用
-(instancetype)initWithCoder:(NSCoder*)coderNS_UNAVAILABLE;
// 與UIWebView一樣的加載請求API
-(nullableWKNavigation*)loadRequest:(NSURLRequest*)request;
// 加載URL
-(nullableWKNavigation*)loadFileURL:(NSURL*)URLallowingReadAccessToURL:(NSURL*)readAccessURLNS_AVAILABLE(10_11,9_0);
// 直接加載HTML
-(nullableWKNavigation*)loadHTMLString:(NSString*)stringbaseURL:(nullableNSURL*)baseURL;
// 直接加載data
-(nullableWKNavigation*)loadData:(NSData*)dataMIMEType:(NSString*)MIMETypecharacterEncodingName:(NSString*)characterEncodingNamebaseURL:(NSURL*)baseURLNS_AVAILABLE(10_11,9_0);
// 前進或者后退到某一頁面
-(nullableWKNavigation*)goToBackForwardListItem:(WKBackForwardListItem*)item;
// 頁面的標題,這昆支持KVO的
@property(nullable,nonatomic,readonly,copy)NSString*title;
// 當前請求的URL,它是支持KVO的
@property(nullable,nonatomic,readonly,copy)NSURL*URL;
// 標識當前是否正在加載內容中,它是支持KVO的
@property(nonatomic,readonly,getter=isLoading)BOOLloading;
// 當前加載的進度,范圍為[0, 1]
@property(nonatomic,readonly)doubleestimatedProgress;
// 標識頁面中的所有資源是否通過安全加密連接來加載,它是支持KVO的
@property(nonatomic,readonly)BOOLhasOnlySecureContent;
// 當前導航的證書鏈,支持KVO
@property(nonatomic,readonly,copy)NSArray*certificateChainNS_AVAILABLE(10_11,9_0);
// 是否可以招待goback操作,它是支持KVO的
@property(nonatomic,readonly)BOOLcanGoBack;
// 是否可以執行gofarward操作,支持KVO
@property(nonatomic,readonly)BOOLcanGoForward;
// 返回上一頁面,如果不能返回,則什么也不干
-(nullableWKNavigation*)goBack;
// 進入下一頁面,如果不能前進,則什么也不干
-(nullableWKNavigation*)goForward;
// 重新載入頁面
-(nullableWKNavigation*)reload;
// 重新從原始URL載入
-(nullableWKNavigation*)reloadFromOrigin;
// 停止加載數據
-(void)stopLoading;
// 執行JS代碼
-(void)evaluateJavaScript:(NSString*)javaScriptStringcompletionHandler:(void(^__nullable)(__nullableid,NSError*__nullableerror))completionHandler;
// 標識是否支持左、右swipe手勢是否可以前進、后退
@property(nonatomic)BOOLallowsBackForwardNavigationGestures;
// 自定義user agent,如果沒有則為nil
@property(nullable,nonatomic,copy)NSString*customUserAgentNS_AVAILABLE(10_11,9_0);
// 在iOS上默認為NO,標識不允許鏈接預覽
@property(nonatomic)BOOLallowsLinkPreviewNS_AVAILABLE(10_11,9_0);
#if TARGET_OS_IPHONE
/*! @abstract The scroll view associated with the web view.
*/
@property(nonatomic,readonly,strong)UIScrollView*scrollView;
#endif
#if !TARGET_OS_IPHONE
// 標識是否支持放大手勢,默認為NO
@property(nonatomic)BOOLallowsMagnification;
// 放大因子,默認為1
@property(nonatomic)CGFloatmagnification;
// 根據設置的縮放因子來縮放頁面,并居中顯示結果在指定的點
-(void)setMagnification:(CGFloat)magnificationcenteredAtPoint:(CGPoint)point;
#endif
WKWebViewConfiguration配置
WKWebViewConfiguration*config=[[WKWebViewConfigurationalloc]init];
目前在iOS平臺上偏好設置只有三個屬性可以設置,如下:
// 設置偏好設置
config.preferences=[[WKPreferencesalloc]init];
// 默認為0
config.preferences.minimumFontSize=10;
// 默認認為YES
config.preferences.javaScriptEnabled=YES;
// 在iOS上默認為NO,表示不能自動通過窗口打開
config.preferences.javaScriptCanOpenWindowsAutomatically=NO;
WKProcessPool內容處理池
WKProcessPool并沒有公開任何的屬性或者方法,不需要配置:
config.processPool=[[WKProcessPoolalloc]init];
其實我們也沒有必須去創建它。
WKUserContentController內容交互控制器
我們要通過JS與webview內容交互,就需要到這個類了,它的所有屬性及方法說明如下:
// 只讀屬性,所有添加的WKUserScript都在這里可以獲取到
@property(nonatomic,readonly,copy)NSArray*userScripts;
// 注入JS
-(void)addUserScript:(WKUserScript*)userScript;
// 移除所有注入的JS
-(void)removeAllUserScripts;
// 添加scriptMessageHandler到所有的frames中,則都可以通過
// window.webkit.messageHandlers..postMessage()
// 發送消息
// 比如,JS要調用我們原生的方法,就可以通過這種方式了
-(void)addScriptMessageHandler:(id)scriptMessageHandlername:(NSString*)name;
// 根據name移除所注入的scriptMessageHandler
-(void)removeScriptMessageHandlerForName:(NSString*)name;
WKUserScript
在WKUserContentController中,所有使用到WKUserScript。WKUserContentController是用于與JS交互的類,而所注入的JS是WKUserScript對象。它的所有屬性和方法如下:
// JS源代碼
@property(nonatomic,readonly,copy)NSString*source;
// JS注入時間
@property(nonatomic,readonly)WKUserScriptInjectionTimeinjectionTime;
// 只讀屬性,表示JS是否應該注入到所有的frames中還是只有main frame.
@property(nonatomic,readonly,getter=isForMainFrameOnly)BOOLforMainFrameOnly;
// 初始化方法,用于創建WKUserScript對象
// source:JS源代碼
// injectionTime:JS注入的時間
// forMainFrameOnly:是否只注入main frame
-(instancetype)initWithSource:(NSString*)sourceinjectionTime:(WKUserScriptInjectionTime)injectionTimeforMainFrameOnly:(BOOL)forMainFrameOnly;
WKUserScriptInjectionTime
typedefNS_ENUM(NSInteger,WKUserScriptInjectionTime){
WKUserScriptInjectionTimeAtDocumentStart,
WKUserScriptInjectionTimeAtDocumentEnd
}NS_ENUM_AVAILABLE(10_10,8_0);
它是一個枚舉類型,只有在文檔開始加載時注入和加載結束時注入。
WKWebsiteDataStore存儲的Web內容
iOS9.0以后才能使用這個類。它是代表webview不同的數據類型,包括cookies、disk、memory caches、WebSQL、IndexedDB數據庫和本地存儲。
從這里看,要優化Webview好像可以通過它來實現,不過要求iOS9.0以上才能使用。現在6.0都沒有拋棄的我,從來不能考慮這種最新的。
// 默認數據存儲
+(WKWebsiteDataStore*)defaultDataStore;
// 返回非持久化存儲,數據不會寫入文件系統
+(WKWebsiteDataStore*)nonPersistentDataStore;
// 已經不可用
-(instancetype)initNS_UNAVAILABLE;
// 只讀屬性,表示是否是持久化存儲
@property(nonatomic,readonly,getter=isPersistent)BOOLpersistent;
// 獲取所有web內容的數據存儲類型集,比如cookies、disk等
+(NSSet*)allWebsiteDataTypes;
// 獲取某些指定數據存儲類型的數據
-(void)fetchDataRecordsOfTypes:(NSSet*)dataTypescompletionHandler:(void(^)(NSArray*))completionHandler;
// 刪除某些指定類型的數據
-(void)removeDataOfTypes:(NSSet*)dataTypesforDataRecords:(NSArray*)dataRecordscompletionHandler:(void(^)(void))completionHandler;
// 刪除某些指定類型的數據且修改日期是指定的日期
-(void)removeDataOfTypes:(NSSet*)websiteDataTypesmodifiedSince:(NSDate*)datecompletionHandler:(void(^)(void))completionHandler;
所有的dataTypes是下面這些系統所定義的:
WK_EXTERNNSString*constWKWebsiteDataTypeDiskCacheNS_AVAILABLE(10_11,9_0);
WK_EXTERNNSString*constWKWebsiteDataTypeMemoryCacheNS_AVAILABLE(10_11,9_0);
WK_EXTERNNSString*constWKWebsiteDataTypeOfflineWebApplicationCacheNS_AVAILABLE(10_11,9_0);
WK_EXTERNNSString*constWKWebsiteDataTypeCookiesNS_AVAILABLE(10_11,9_0);
WK_EXTERNNSString*constWKWebsiteDataTypeSessionStorageNS_AVAILABLE(10_11,9_0);
WK_EXTERNNSString*constWKWebsiteDataTypeLocalStorageNS_AVAILABLE(10_11,9_0);
WK_EXTERNNSString*constWKWebsiteDataTypeWebSQLDatabasesNS_AVAILABLE(10_11,9_0);
WK_EXTERNNSString*constWKWebsiteDataTypeIndexedDBDatabasesNS_AVAILABLE(10_11,9_0);
WKWebsiteDataRecord
iOS9.0以后才可用。
website的數據存儲記錄類型,它只有兩個屬性:
// 通常是域名
@property(nonatomic,readonly,copy)NSString*displayName;
// 存儲的數據類型集
@property(nonatomic,readonly,copy)NSSet*dataTypes;
WKSelectionGranularity選擇粒度
它表示在webview上選擇內容的粒度,只有下面這兩種類型:
typedefNS_ENUM(NSInteger,WKSelectionGranularity){
WKSelectionGranularityDynamic,
WKSelectionGranularityCharacter,
}NS_ENUM_AVAILABLE_IOS(8_0);
它是用于webview內容交互時選擇內容的粒度類型設置。比如說,當使用WKSelectionGranularityDynamic時,而所選擇的內容是單個塊,這時候granularity可能會是單個字符;當所選擇的web內容不限制于某個塊時,granularity可能會是單個塊。
WKNavigationDelegate
@protocolWKNavigationDelegate
@optional
// 決定導航的動作,通常用于處理跨域的鏈接能否導航。WebKit對跨域進行了安全檢查限制,不允許跨域,因此我們要對不能跨域的鏈接
// 單獨處理。但是,對于Safari是允許跨域的,不用這么處理。
// 這個是決定是否Request
-(void)webView:(WKWebView*)webViewdecidePolicyForNavigationAction:(WKNavigationAction*)navigationActiondecisionHandler:(void(^)(WKNavigationActionPolicy))decisionHandler;
// 決定是否接收響應
// 這個是決定是否接收response
// 要獲取response,通過WKNavigationResponse對象獲取
-(void)webView:(WKWebView*)webViewdecidePolicyForNavigationResponse:(WKNavigationResponse*)navigationResponsedecisionHandler:(void(^)(WKNavigationResponsePolicy))decisionHandler;
// 當main frame的導航開始請求時,會調用此方法
-(void)webView:(WKWebView*)webViewdidStartProvisionalNavigation:(null_unspecifiedWKNavigation*)navigation;
// 當main frame接收到服務重定向時,會回調此方法
-(void)webView:(WKWebView*)webViewdidReceiveServerRedirectForProvisionalNavigation:(null_unspecifiedWKNavigation*)navigation;
// 當main frame開始加載數據失敗時,會回調
-(void)webView:(WKWebView*)webViewdidFailProvisionalNavigation:(null_unspecifiedWKNavigation*)navigationwithError:(NSError*)error;
// 當main frame的web內容開始到達時,會回調
-(void)webView:(WKWebView*)webViewdidCommitNavigation:(null_unspecifiedWKNavigation*)navigation;
// 當main frame導航完成時,會回調
-(void)webView:(WKWebView*)webViewdidFinishNavigation:(null_unspecifiedWKNavigation*)navigation;
// 當main frame最后下載數據失敗時,會回調
-(void)webView:(WKWebView*)webViewdidFailNavigation:(null_unspecifiedWKNavigation*)navigationwithError:(NSError*)error;
// 這與用于授權驗證的API,與AFN、UIWebView的授權驗證API是一樣的
-(void)webView:(WKWebView*)webViewdidReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge*)challengecompletionHandler:(void(^)(NSURLSessionAuthChallengeDispositiondisposition,NSURLCredential*__nullablecredential))completionHandler;
// 當web content處理完成時,會回調
-(void)webViewWebContentProcessDidTerminate:(WKWebView*)webViewNS_AVAILABLE(10_11,9_0);
@end
WKNavigationActionPolicy
導航動作決定策略:
typedefNS_ENUM(NSInteger,WKNavigationActionPolicy){
WKNavigationActionPolicyCancel,
WKNavigationActionPolicyAllow,
}NS_ENUM_AVAILABLE(10_10,8_0);
它是枚舉類型,只有Cancel和Allow這兩種。設置為Cancel就是不允許導航,就不會跳轉鏈接。
WKNavigationResponsePolicy
typedefNS_ENUM(NSInteger,WKNavigationResponsePolicy){
WKNavigationResponsePolicyCancel,
WKNavigationResponsePolicyAllow,
}NS_ENUM_AVAILABLE(10_10,8_0);
WKNavigationResponse
WKNavigationResponse是導航響應類,通過它可以獲取相關響應的信息:
NS_CLASS_AVAILABLE(10_10,8_0)
@interfaceWKNavigationResponse: NSObject
// 是否是main frame
@property(nonatomic,readonly,getter=isForMainFrame)BOOLforMainFrame;
// 獲取響應response
@property(nonatomic,readonly,copy)NSURLResponse*response;
// 是否顯示MIMEType
@property(nonatomic,readonly)BOOLcanShowMIMEType;
@end
只有接收響應與不接收響應兩種。
WKNavigationAction
WKNavigationAction對象包含關于導航的action的信息,用于make policy decisions。它只有以下幾個屬性:
// 正在請求的導航的frame
@property(nonatomic,readonly,copy)WKFrameInfo*sourceFrame;
// 目標frame,如果這是新的window,它會是nil
@property(nullable,nonatomic,readonly,copy)WKFrameInfo*targetFrame;
// 導航類型,如下面的小標題WKNavigationType
@property(nonatomic,readonly)WKNavigationTypenavigationType;
// 導航的請求
@property(nonatomic,readonly,copy)NSURLRequest*request;
WKNavigationType
WKNavigationType類型是枚舉類型,它的可選值如下:
typedefNS_ENUM(NSInteger,WKNavigationType){
// 鏈接已經點擊
WKNavigationTypeLinkActivated,
// 表單提交
WKNavigationTypeFormSubmitted,
// 前進、后退
WKNavigationTypeBackForward,
// 重新載入
WKNavigationTypeReload,
// 表單重新提交
WKNavigationTypeFormResubmitted,
// 其它
WKNavigationTypeOther=-1,
}NS_ENUM_AVAILABLE(10_10,8_0);
WKUIDelegate
@protocolWKUIDelegate
@optional
// 創建新的webview
// 可以指定配置對象、導航動作對象、window特性
-(nullableWKWebView*)webView:(WKWebView*)webViewcreateWebViewWithConfiguration:(WKWebViewConfiguration*)configurationforNavigationAction:(WKNavigationAction*)navigationActionwindowFeatures:(WKWindowFeatures*)windowFeatures;
// webview關閉時回調
-(void)webViewDidClose:(WKWebView*)webViewNS_AVAILABLE(10_11,9_0);
// 調用JS的alert()方法
-(void)webView:(WKWebView*)webViewrunJavaScriptAlertPanelWithMessage:(NSString*)messageinitiatedByFrame:(WKFrameInfo*)framecompletionHandler:(void(^)(void))completionHandler;
// 調用JS的confirm()方法
-(void)webView:(WKWebView*)webViewrunJavaScriptConfirmPanelWithMessage:(NSString*)messageinitiatedByFrame:(WKFrameInfo*)framecompletionHandler:(void(^)(BOOLresult))completionHandler;
// 調用JS的prompt()方法
-(void)webView:(WKWebView*)webViewrunJavaScriptTextInputPanelWithPrompt:(NSString*)promptdefaultText:(nullableNSString*)defaultTextinitiatedByFrame:(WKFrameInfo*)framecompletionHandler:(void(^)(NSString*__nullableresult))completionHandler;
@end
WKBackForwardList
WKBackForwardList表示webview中可以前進或者后退的頁面列表。其聲明如下:
NS_CLASS_AVAILABLE(10_10,8_0)
@interfaceWKBackForwardList: NSObject
// 當前正在顯示的item(頁面)
@property(nullable,nonatomic,readonly,strong)WKBackForwardListItem*currentItem;
// 后一頁,如果沒有就是nil
@property(nullable,nonatomic,readonly,strong)WKBackForwardListItem*backItem;
// 前一頁,如果沒有就是nil
@property(nullable,nonatomic,readonly,strong)WKBackForwardListItem*forwardItem;
// 根據下標獲取某一個頁面的item
-(nullableWKBackForwardListItem*)itemAtIndex:(NSInteger)index;
// 可以進行goback操作的頁面列表
@property(nonatomic,readonly,copy)NSArray*backList;
// 可以進行goforward操作的頁面列表
@property(nonatomic,readonly,copy)NSArray*forwardList;
@end
WKBackForwardListItem
頁面導航前進、后退列表項:
NS_CLASS_AVAILABLE(10_10,8_0)
@interfaceWKBackForwardListItem: NSObject
// 該頁面的URL
@property(readonly,copy)NSURL*URL;
// 該頁面的title
@property(nullable,readonly,copy)NSString*title;
// 初始請求該item的請求的URL
@property(readonly,copy)NSURL*initialURL;
@end
本篇文章只是講解了WKWebView所有相關的類的API,先閱讀過本篇文章,再繼續往下閱讀實戰篇文章!