** 解决 webView 加载 含有 中文的 URL 问题
将URL 中的 中文以及其他非英文字符 进行转换 URLEncode
extension String {
func urlEncodeIfNeed() -> String {
if let url:URL = URL(string: self){
if(UIApplication.shared.canOpenURL(url) == true){
return self;
}
}
return NSString.init(string: self).addingPercentEncoding(withAllowedCharacters: NSCharacterSet.urlQueryAllowed)!
}
}
** 清除webView 缓存
let websetDataType = WKWebsiteDataStore.allWebsiteDataTypes();
let dateFrom:NSDate = NSDate.init(timeIntervalSince1970: 0)
WKWebsiteDataStore.default().removeData(ofTypes: websetDataType, modifiedSince: dateFrom as Date, completionHandler: {
print("clear done")
})
//其中 WKWebsiteDataStory 的 类型有
let cookie = WKWebsiteDataTypeCookies;//网址的cookies
let disCache = WKWebsiteDataTypeDiskCache;//磁盘缓存文件,比如图片文件
let WebApplicationCache = WKWebsiteDataTypeOfflineWebApplicationCache;//离线数据
let MemoryCache = WKWebsiteDataTypeMemoryCache;//内存缓存
let LocalStorage = WKWebsiteDataTypeLocalStorage;//网站通过代码写入到本地的数据
let SessionStorage = WKWebsiteDataTypeSessionStorage;//网站通过代码写入到本地的session
let IndexedDBDatabases = WKWebsiteDataTypeIndexedDBDatabases;//
let WebSQLDatabases = WKWebsiteDataTypeWebSQLDatabases;//
如果是 IOS 8 不支持以上清除缓存的方式 ,兼容清除, 以及手动删除Library/Caches文件夹等
http://mft.iteye.com/admin/blogs/2381013
也可以直接根据需要删除 document 下的文件夹
http://mft.iteye.com/admin/blogs/2394856
** 解决 target = "_blank" 打开新窗口问题
import WebKit
Extend your class with WKUIDelegate
Set delegate for webview
self.webView.uiDelegate = self
Implement protocol method
func webView(_ webView: WKWebView, createWebViewWith configuration: WKWebViewConfiguration, for navigationAction: WKNavigationAction, windowFeatures: WKWindowFeatures) -> WKWebView? {
if navigationAction.targetFrame == nil {
//webView.load(navigationAction.request)
print(navigationAction.request);
print("new target")
}
return nil
}
** 获取上一个页面的URL
wb.backForwardList.backItem?.url.absoluteString
** 判断当前 加载的页面 是通过 返回 还是 前进 或者提交表单等
func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
if(navigationAction.navigationType != .backForward){
}
** 去掉 下拉 时的 橡皮筋效果
wkWebView.scrollView.bounces = false;
** 加载 hml 字符串
let jsUrl:String = "https://xw.qq.com";
var source:String = "";
let js_url = NSURL(string: jsUrl);
do {
print("1")
let data = try NSString(contentsOf: js_url! as URL, encoding: UInt(String.Encoding.utf8.hashValue))
print("2")
source = data as String;
print(source);
print("3")
} catch {
print("jjj false")
}
print("done")
if(source != ""){
let wk:WKWebView = WKWebView(frame: self.view.frame);
wk.loadHTMLString(source, baseURL: js_url! as URL)
self.view.addSubview(wk)
}
--------------------------------WKWebView 其他相关 知识 参考 ----------------------------------------------
swift -> WKWebView 滚动 监听 ,设置 滚动位置
swift -> WKWebview 长按 获取 html 标签