1. 程式人生 > >UIWebView 無縫切換到 WKWebView

UIWebView 無縫切換到 WKWebView

count tle don 都是 data from top uiwebview http


WKWebView 是IOS8新增的 Web瀏覽視圖


長處: 載入速度 比UIWebView提升差點兒相同一倍的, 內存使用上面,反而還少了一半。

缺點: WKWebView 不支持緩存 和 NSURLProtocol 攔截了


我建議假設對緩存不高的頁面能夠使用。用戶體驗會提高非常多。


因為項目中曾經都是用 UIWebView 並且還要兼容 IOS8 之前的機子。 所以 我創建了一個新類 IMYWebView 你僅僅要全局替換 UIWebView 就能無縫升級到 WKWebView 啦


IMYWebView.h 中的API 會在內部自己主動支持 UIWebView 和 WKWebView。

title,estimatedProgress 是我覺得 WKWebView 中比較實用的新增API

@interface IMYVKWebView : UIView

///使用UIWebView
- (instancetype)initWithFrame:(CGRect)frame usingUIWebView:(BOOL)usingUIWebView;

@property(weak,nonatomic)id<IMYVKWebViewDelegate> delegate;

///內部使用的webView
@property (nonatomic, readonly) id realWebView;
///是否正在使用 UIWebView
@property (nonatomic, readonly) BOOL usingUIWebView;
///預估網頁載入進度
@property (nonatomic, readonly) double estimatedProgress;

@property (nonatomic, readonly) NSURLRequest *originRequest;

///back 層數
- (NSInteger)countOfHistory;
- (void)gobackWithStep:(NSInteger)step;

///---- UI 或者 WK 的API
@property (nonatomic, readonly) UIScrollView *scrollView;

- (id)loadRequest:(NSURLRequest *)request;
- (id)loadHTMLString:(NSString *)string baseURL:(NSURL *)baseURL;

@property (nonatomic, readonly, copy) NSString *title;
@property (nonatomic, readonly) NSURLRequest *currentRequest;
@property (nonatomic, readonly) NSURL *URL;

@property (nonatomic, readonly, getter=isLoading) BOOL loading;
@property (nonatomic, readonly) BOOL canGoBack;
@property (nonatomic, readonly) BOOL canGoForward;

- (id)goBack;
- (id)goForward;
- (id)reload;
- (id)reloadFromOrigin;
- (void)stopLoading;

- (void)evaluateJavaScript:(NSString *)javaScriptString completionHandler:(void (^)(id, NSError *))completionHandler;
///不建議使用這個辦法  由於會在內部等待webView 的運行結果
- (NSString *)stringByEvaluatingJavaScriptFromString:(NSString *)javaScriptString __deprecated_msg("Method deprecated. Use [evaluateJavaScript:completionHandler:]");

///是否依據視圖大小來縮放頁面  默覺得YES
@property (nonatomic) BOOL scalesPageToFit;

@end


代碼地址

UIWebView 無縫切換到 WKWebView