SwiftWebVC.swift 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  1. //
  2. // SwiftWebVC.swift
  3. //
  4. // Created by Myles Ringle on 24/06/2015.
  5. // Transcribed from code used in SVWebViewController.
  6. // Copyright (c) 2015 Myles Ringle & Sam Vermette. All rights reserved.
  7. //
  8. import WebKit
  9. public protocol SwiftWebVCDelegate: class {
  10. func didStartLoading()
  11. func didReceiveServerRedirectForProvisionalNavigation(url: URL)
  12. func didFinishLoading(success: Bool)
  13. func didFinishLoading(success: Bool, url: URL)
  14. func webDismiss()
  15. }
  16. public class SwiftWebVC: UIViewController {
  17. public weak var delegate: SwiftWebVCDelegate?
  18. var storedStatusColor: UIBarStyle?
  19. var buttonColor: UIColor? = nil
  20. var titleColor: UIColor? = nil
  21. var closing: Bool! = false
  22. lazy var backBarButtonItem: UIBarButtonItem = {
  23. var tempBackBarButtonItem = UIBarButtonItem(image: SwiftWebVC.bundledImage(named: "SwiftWebVCBack"),
  24. style: UIBarButtonItem.Style.plain,
  25. target: self,
  26. action: #selector(SwiftWebVC.goBackTapped(_:)))
  27. tempBackBarButtonItem.width = 18.0
  28. tempBackBarButtonItem.tintColor = self.buttonColor
  29. return tempBackBarButtonItem
  30. }()
  31. lazy var forwardBarButtonItem: UIBarButtonItem = {
  32. var tempForwardBarButtonItem = UIBarButtonItem(image: SwiftWebVC.bundledImage(named: "SwiftWebVCNext"),
  33. style: UIBarButtonItem.Style.plain,
  34. target: self,
  35. action: #selector(SwiftWebVC.goForwardTapped(_:)))
  36. tempForwardBarButtonItem.width = 18.0
  37. tempForwardBarButtonItem.tintColor = self.buttonColor
  38. return tempForwardBarButtonItem
  39. }()
  40. lazy var refreshBarButtonItem: UIBarButtonItem = {
  41. var tempRefreshBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.refresh,
  42. target: self,
  43. action: #selector(SwiftWebVC.reloadTapped(_:)))
  44. tempRefreshBarButtonItem.tintColor = self.buttonColor
  45. return tempRefreshBarButtonItem
  46. }()
  47. lazy var stopBarButtonItem: UIBarButtonItem = {
  48. var tempStopBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.stop,
  49. target: self,
  50. action: #selector(SwiftWebVC.stopTapped(_:)))
  51. tempStopBarButtonItem.tintColor = self.buttonColor
  52. return tempStopBarButtonItem
  53. }()
  54. lazy var actionBarButtonItem: UIBarButtonItem = {
  55. var tempActionBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.action,
  56. target: self,
  57. action: #selector(SwiftWebVC.actionButtonTapped(_:)))
  58. tempActionBarButtonItem.tintColor = self.buttonColor
  59. return tempActionBarButtonItem
  60. }()
  61. lazy var webView: WKCookieWebView = {
  62. var tempWebView = WKCookieWebView(frame: UIScreen.main.bounds, configuration: WKWebViewConfiguration(), useRedirectCookieHandling: true)
  63. tempWebView.uiDelegate = self
  64. tempWebView.navigationDelegate = self
  65. return tempWebView;
  66. }()
  67. var request: URLRequest!
  68. var navBarTitle: UILabel!
  69. var hideToolbar = false
  70. ////////////////////////////////////////////////
  71. deinit {
  72. webView.stopLoading()
  73. UIApplication.shared.isNetworkActivityIndicatorVisible = false
  74. webView.uiDelegate = nil;
  75. webView.navigationDelegate = nil;
  76. }
  77. public convenience init(urlString: String, hideToolbar: Bool) {
  78. self.init(pageURL: URL(string: urlString)!, hideToolbar: hideToolbar)
  79. }
  80. public convenience init(pageURL: URL, hideToolbar: Bool) {
  81. self.init(aRequest: URLRequest(url: pageURL), hideToolbar: hideToolbar)
  82. }
  83. public convenience init(aRequest: URLRequest, hideToolbar: Bool) {
  84. self.init()
  85. self.request = aRequest
  86. self.hideToolbar = hideToolbar
  87. }
  88. ////////////////////////////////////////////////
  89. // View Lifecycle
  90. override public func loadView() {
  91. view = webView
  92. let language = NSLocale.preferredLanguages[0] as String
  93. request.setValue(CCUtility.getUserAgent(), forHTTPHeaderField: "User-Agent")
  94. request.addValue("true", forHTTPHeaderField: "OCS-APIRequest")
  95. request.addValue(language, forHTTPHeaderField: "Accept-Language")
  96. _ = webView.load(request)
  97. }
  98. override public func viewDidLoad() {
  99. super.viewDidLoad()
  100. updateToolbarItems()
  101. }
  102. override public func viewWillAppear(_ animated: Bool) {
  103. assert(self.navigationController != nil, "SVWebViewController needs to be contained in a UINavigationController. If you are presenting SVWebViewController modally, use SVModalWebViewController instead.")
  104. navBarTitle = UILabel()
  105. navBarTitle.backgroundColor = UIColor.clear
  106. if presentingViewController == nil {
  107. if let titleAttributes = navigationController!.navigationBar.titleTextAttributes {
  108. navBarTitle.textColor = titleAttributes[NSAttributedString.Key.foregroundColor] as? UIColor //[titleAttributes:"NSColor"] // ["NSColor"] as! UIColor
  109. }
  110. }
  111. else {
  112. navBarTitle.textColor = self.titleColor
  113. }
  114. navBarTitle.shadowOffset = CGSize(width: 0, height: 1);
  115. navBarTitle.font = UIFont(name: "HelveticaNeue-Medium", size: 17.0)
  116. navigationItem.titleView = navBarTitle;
  117. super.viewWillAppear(true)
  118. if (UIDevice.current.userInterfaceIdiom == UIUserInterfaceIdiom.phone) {
  119. self.navigationController?.setToolbarHidden(false, animated: false)
  120. }
  121. else if (UIDevice.current.userInterfaceIdiom == UIUserInterfaceIdiom.pad) {
  122. self.navigationController?.setToolbarHidden(true, animated: true)
  123. }
  124. self.navigationController?.setToolbarHidden(hideToolbar, animated: false)
  125. }
  126. override public func viewWillDisappear(_ animated: Bool) {
  127. super.viewWillDisappear(true)
  128. if (UIDevice.current.userInterfaceIdiom == UIUserInterfaceIdiom.phone) {
  129. self.navigationController?.setToolbarHidden(true, animated: true)
  130. }
  131. }
  132. override public func viewDidDisappear(_ animated: Bool) {
  133. super.viewDidDisappear(true)
  134. UIApplication.shared.isNetworkActivityIndicatorVisible = false
  135. }
  136. override public func dismiss(animated flag: Bool, completion: (() -> Void)? = nil) {
  137. super.dismiss(animated: flag, completion: {
  138. self.delegate?.webDismiss()
  139. })
  140. }
  141. ////////////////////////////////////////////////
  142. // Toolbar
  143. func updateToolbarItems() {
  144. backBarButtonItem.isEnabled = webView.canGoBack
  145. forwardBarButtonItem.isEnabled = webView.canGoForward
  146. let refreshStopBarButtonItem: UIBarButtonItem = webView.isLoading ? stopBarButtonItem : refreshBarButtonItem
  147. let fixedSpace: UIBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.fixedSpace, target: nil, action: nil)
  148. let flexibleSpace: UIBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.flexibleSpace, target: nil, action: nil)
  149. if (UIDevice.current.userInterfaceIdiom == UIUserInterfaceIdiom.pad) {
  150. let toolbarWidth: CGFloat = 250.0
  151. fixedSpace.width = 35.0
  152. let items: NSArray = [fixedSpace, refreshStopBarButtonItem, fixedSpace, backBarButtonItem, fixedSpace, forwardBarButtonItem, fixedSpace, actionBarButtonItem]
  153. let toolbar: UIToolbar = UIToolbar(frame: CGRect(x: 0.0, y: 0.0, width: toolbarWidth, height: 44.0))
  154. if !closing {
  155. toolbar.items = items as? [UIBarButtonItem]
  156. if presentingViewController == nil {
  157. toolbar.barTintColor = navigationController?.navigationBar.barTintColor
  158. }
  159. else {
  160. toolbar.barStyle = (navigationController?.navigationBar.barStyle)!
  161. }
  162. toolbar.tintColor = navigationController?.navigationBar.tintColor
  163. }
  164. navigationItem.rightBarButtonItems = items.reverseObjectEnumerator().allObjects as? [UIBarButtonItem]
  165. }
  166. else {
  167. let items: NSArray = [fixedSpace, backBarButtonItem, flexibleSpace, forwardBarButtonItem, flexibleSpace, refreshStopBarButtonItem, flexibleSpace, actionBarButtonItem, fixedSpace]
  168. if !closing {
  169. if presentingViewController == nil {
  170. navigationController?.toolbar.barTintColor = navigationController?.navigationBar.barTintColor
  171. }
  172. else {
  173. navigationController?.toolbar.barStyle = (navigationController?.navigationBar.barStyle)!
  174. }
  175. navigationController?.toolbar.tintColor = navigationController?.navigationBar.tintColor
  176. toolbarItems = items as? [UIBarButtonItem]
  177. }
  178. }
  179. }
  180. ////////////////////////////////////////////////
  181. // Target Actions
  182. @objc func goBackTapped(_ sender: UIBarButtonItem) {
  183. webView.goBack()
  184. }
  185. @objc func goForwardTapped(_ sender: UIBarButtonItem) {
  186. webView.goForward()
  187. }
  188. @objc func reloadTapped(_ sender: UIBarButtonItem) {
  189. webView.reload()
  190. }
  191. @objc func stopTapped(_ sender: UIBarButtonItem) {
  192. webView.stopLoading()
  193. updateToolbarItems()
  194. }
  195. @objc func actionButtonTapped(_ sender: AnyObject) {
  196. if let url: URL = ((webView.url != nil) ? webView.url : request.url) {
  197. let activities: NSArray = [SwiftWebVCActivitySafari(), SwiftWebVCActivityChrome()]
  198. if url.absoluteString.hasPrefix("file:///") {
  199. let dc: UIDocumentInteractionController = UIDocumentInteractionController(url: url)
  200. dc.presentOptionsMenu(from: view.bounds, in: view, animated: true)
  201. }
  202. else {
  203. let activityController: UIActivityViewController = UIActivityViewController(activityItems: [url], applicationActivities: activities as? [UIActivity])
  204. if floor(NSFoundationVersionNumber) > NSFoundationVersionNumber_iOS_7_1 && UIDevice.current.userInterfaceIdiom == UIUserInterfaceIdiom.pad {
  205. let ctrl: UIPopoverPresentationController = activityController.popoverPresentationController!
  206. ctrl.sourceView = view
  207. ctrl.barButtonItem = sender as? UIBarButtonItem
  208. }
  209. present(activityController, animated: true, completion: nil)
  210. }
  211. }
  212. }
  213. ////////////////////////////////////////////////
  214. @objc func doneButtonTapped() {
  215. closing = true
  216. UINavigationBar.appearance().barStyle = storedStatusColor!
  217. self.dismiss(animated: true, completion: nil)
  218. }
  219. // MARK: - Class Methods
  220. /// Helper function to get image within SwiftWebVCResources bundle
  221. ///
  222. /// - parameter named: The name of the image in the SwiftWebVCResources bundle
  223. class func bundledImage(named: String) -> UIImage? {
  224. let image = UIImage(named: named)
  225. if image == nil {
  226. return UIImage(named: named, in: Bundle(for: SwiftWebVC.classForCoder()), compatibleWith: nil)
  227. } // Replace MyBasePodClass with yours
  228. return image
  229. }
  230. }
  231. extension SwiftWebVC: WKUIDelegate {
  232. // Add any desired WKUIDelegate methods here: https://developer.apple.com/reference/webkit/wkuidelegate
  233. }
  234. extension SwiftWebVC: WKNavigationDelegate {
  235. public func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
  236. self.delegate?.didStartLoading()
  237. UIApplication.shared.isNetworkActivityIndicatorVisible = true
  238. updateToolbarItems()
  239. }
  240. public func webView(_ webView: WKWebView, didReceiveServerRedirectForProvisionalNavigation navigation: WKNavigation!) {
  241. self.delegate?.didReceiveServerRedirectForProvisionalNavigation(url: webView.url!)
  242. }
  243. public func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
  244. self.delegate?.didFinishLoading(success: true)
  245. self.delegate?.didFinishLoading(success: true, url: webView.url!)
  246. UIApplication.shared.isNetworkActivityIndicatorVisible = false
  247. webView.evaluateJavaScript("document.title") { result, error in
  248. guard let title = result as? String else { return }
  249. if (error == nil && self.navBarTitle != nil) {
  250. self.navBarTitle.text = String(describing: title)
  251. self.navBarTitle.sizeToFit()
  252. self.updateToolbarItems()
  253. }
  254. }
  255. }
  256. public func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
  257. decisionHandler(.allow)
  258. }
  259. public func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
  260. self.delegate?.didFinishLoading(success: false)
  261. self.delegate?.didFinishLoading(success: false, url: webView.url!)
  262. UIApplication.shared.isNetworkActivityIndicatorVisible = false
  263. updateToolbarItems()
  264. }
  265. public func webView(_ webView: WKWebView, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
  266. if let serverTrust = challenge.protectionSpace.serverTrust {
  267. completionHandler(Foundation.URLSession.AuthChallengeDisposition.useCredential, URLCredential(trust: serverTrust))
  268. } else {
  269. completionHandler(URLSession.AuthChallengeDisposition.useCredential, nil);
  270. }
  271. }
  272. }