PQBaseWebViewController.swift 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184
  1. //
  2. // PQBaseWebViewController.swift
  3. // PQSpeed
  4. //
  5. // Created by SanW on 2020/5/27.
  6. // Copyright © 2020 BytesFlow. All rights reserved.
  7. //
  8. import UIKit
  9. import WebKit
  10. public class PQBaseWebViewController: PQBaseViewController {
  11. var emptyData: PQEmptyModel? = {
  12. let emptyData = PQEmptyModel()
  13. emptyData.title = "网页加载失败,请重试~"
  14. emptyData.emptyImage = "pic_network"
  15. return emptyData
  16. }()
  17. lazy var webView: WKWebView = {
  18. let config: WKWebViewConfiguration = WKWebViewConfiguration()
  19. config.allowsInlineMediaPlayback = true
  20. let webView: WKWebView = WKWebView(frame: CGRect(x: 0, y: cDevice_iPhoneNavBarAndStatusBarHei, width: cScreenWidth, height: cScreenHeigth - cDevice_iPhoneNavBarAndStatusBarHei), configuration: config)
  21. webView.backgroundColor = UIColor.white
  22. if #available(iOS 11.0, *) {
  23. webView.scrollView.contentInsetAdjustmentBehavior = .never
  24. } else {
  25. automaticallyAdjustsScrollViewInsets = false
  26. }
  27. webView.navigationDelegate = self
  28. return webView
  29. }()
  30. lazy var progresslayer: CALayer = {
  31. let progresslayer = CALayer()
  32. progresslayer.frame = CGRect(x: 0, y: cDevice_iPhoneNavBarAndStatusBarHei, width: cScreenWidth * 0.1, height: 2)
  33. progresslayer.backgroundColor = UIColor.hexColor(hexadecimal: "#FF9500").cgColor
  34. return progresslayer
  35. }()
  36. @objc public var baseUrl: String? {
  37. didSet {
  38. if baseUrl != nil, baseUrl?.count ?? 0 > 0 {
  39. webView.load(URLRequest(url: NSURL(string: baseUrl ?? "")! as URL, cachePolicy: .reloadIgnoringCacheData))
  40. // 添加属性监听
  41. webView.addObserver(self, forKeyPath: "estimatedProgress", options: .new, context: nil)
  42. isAddObserve = true
  43. view.layer.addSublayer(progresslayer)
  44. }
  45. }
  46. }
  47. @objc var baseTitle: String?
  48. public var evaluateJavaScript: String? // 交互
  49. var isAddObserve: Bool = false
  50. override open func viewDidLoad() {
  51. super.viewDidLoad()
  52. // Do any additional setup after loading the view.
  53. view.addSubview(webView)
  54. leftButton(image: "icon_blanc_back")
  55. navHeadImageView?.backgroundColor = UIColor.white
  56. }
  57. override public func viewWillAppear(_ animated: Bool) {
  58. super.viewWillAppear(animated)
  59. if (UIApplication.shared.keyWindow?.viewWithTag(cProtocalViewTag)) != nil {
  60. (UIApplication.shared.keyWindow?.viewWithTag(cProtocalViewTag))?.isHidden = true
  61. }
  62. }
  63. override public func viewWillDisappear(_ animated: Bool) {
  64. super.viewWillDisappear(animated)
  65. if (UIApplication.shared.keyWindow?.viewWithTag(cProtocalViewTag)) != nil {
  66. (UIApplication.shared.keyWindow?.viewWithTag(cProtocalViewTag))?.isHidden = false
  67. }
  68. }
  69. deinit {
  70. if isAddObserve {
  71. webView.removeObserver(self, forKeyPath: "estimatedProgress")
  72. }
  73. }
  74. }
  75. extension PQBaseWebViewController: WKNavigationDelegate {
  76. func refreshClick() {
  77. if baseUrl != nil, baseUrl?.count ?? 0 > 0 {
  78. webView.load(URLRequest(url: NSURL(string: baseUrl ?? "")! as URL, cachePolicy: .useProtocolCachePolicy))
  79. }
  80. }
  81. @objc func back() {
  82. if webView.canGoBack {
  83. webView.goBack()
  84. } else if navigationController != nil {
  85. navigationController?.popViewController(animated: true)
  86. } else {
  87. dismiss(animated: true, completion: nil)
  88. }
  89. }
  90. override public func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey: Any]?, context: UnsafeMutableRawPointer?) {
  91. if keyPath == "estimatedProgress" {
  92. progresslayer.opacity = 1
  93. let float = (change?[NSKeyValueChangeKey.newKey] as! NSNumber).floatValue
  94. progresslayer.frame = CGRect(x: 0, y: cDevice_iPhoneNavBarAndStatusBarHei, width: cScreenWidth * CGFloat(float), height: 3)
  95. if float == 1 {
  96. weak var weakself = self
  97. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.2) {
  98. weakself?.progresslayer.opacity = 0
  99. }
  100. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.8) {
  101. weakself?.progresslayer.frame = CGRect(x: 0, y: cDevice_iPhoneNavBarAndStatusBarHei, width: 0, height: 3)
  102. }
  103. }
  104. } else {
  105. super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context)
  106. }
  107. }
  108. public func webView(_ webView: WKWebView, didFinish _: WKNavigation!) {
  109. if baseTitle == nil || baseTitle?.count ?? 0 <= 0 {
  110. webView.evaluateJavaScript("document.title") { [weak self] (any, _) -> Void in
  111. self?.setTitle(title: any as? String)
  112. self?.baseTitle = any as? String
  113. }
  114. }
  115. if evaluateJavaScript != nil, (evaluateJavaScript?.count ?? 0) > 0 {
  116. webView.evaluateJavaScript(evaluateJavaScript!) { _, _ in
  117. }
  118. }
  119. }
  120. public func webView(_ webView: WKWebView, didFail _: WKNavigation!, withError error: Error) {
  121. BFLog(message: error)
  122. if baseTitle == nil || baseTitle?.count ?? 0 <= 0 {
  123. webView.evaluateJavaScript("document.title") { [weak self] (any, _) -> Void in
  124. self?.setTitle(title: any as? String)
  125. self?.baseTitle = any as? String
  126. }
  127. }
  128. }
  129. public func webView(_: WKWebView, didFailProvisionalNavigation _: WKNavigation!, withError _: Error) {}
  130. public func webView(_: WKWebView, decidePolicyFor navigationResponse: WKNavigationResponse, decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void) {
  131. BFLog(message: "navigationResponse:\(String(describing: navigationResponse))")
  132. decisionHandler(.allow)
  133. }
  134. public func webView(_: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
  135. BFLog(message: "didStartProvisionalNavigation:\(String(describing: navigation))")
  136. }
  137. public func webView(_: WKWebView, didReceiveServerRedirectForProvisionalNavigation navigation: WKNavigation!) {
  138. BFLog(message: "didReceiveServerRedirectForProvisionalNavigation:\(String(describing: navigation))")
  139. }
  140. public func webView(_: WKWebView, didCommit navigation: WKNavigation!) {
  141. BFLog(message: "\(String(describing: navigation))")
  142. }
  143. // func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
  144. // let url : String = navigationAction.request.url?.absoluteString ?? "";
  145. // if(url.count == 0 || url == "about:blank"){
  146. // decisionHandler(.cancel)
  147. // return
  148. // }
  149. // let vc = PQBaseWebViewController.init()
  150. // vc.baseUrl = url
  151. // navigationController?.pushViewController(vc, animated: true)
  152. // BFLog(message: "decidePolicyFor \(String(describing: navigationAction))")
  153. // decisionHandler(.allow)
  154. // }
  155. override public var preferredStatusBarStyle: UIStatusBarStyle {
  156. if #available(iOS 13.0, *) {
  157. return .darkContent
  158. } else {
  159. // Fallback on earlier versions
  160. return .default
  161. }
  162. }
  163. }