BaseWebViewUIViewController.swift 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275
  1. //
  2. // BaseWebViewUIViewController.swift
  3. // O2Platform
  4. //
  5. // Created by 刘振兴 on 2016/10/11.
  6. // Copyright © 2016年 zoneland. All rights reserved.
  7. //
  8. import UIKit
  9. import WebKit
  10. import CocoaLumberjack
  11. import Alamofire
  12. import ObjectMapper
  13. import swiftScan
  14. open class BaseWebViewUIViewController: UIViewController {
  15. var webView:WKWebView!
  16. override open func viewDidLoad() {
  17. super.viewDidLoad()
  18. // Do any additional setup after loading the view.
  19. }
  20. override open func didReceiveMemoryWarning() {
  21. super.didReceiveMemoryWarning()
  22. // Dispose of any resources that can be recreated.
  23. }
  24. open func theWebView(){
  25. setupWebView()
  26. }
  27. public func setupWebView() {
  28. let userContentController = WKUserContentController()
  29. //cookie脚本
  30. if let cookies = HTTPCookieStorage.shared.cookies {
  31. let script = getJSCookiesString(cookies: cookies)
  32. let cookieScript = WKUserScript(source: script, injectionTime: WKUserScriptInjectionTime.atDocumentStart, forMainFrameOnly: false)
  33. userContentController.addUserScript(cookieScript)
  34. }
  35. let webViewConfig = WKWebViewConfiguration()
  36. webViewConfig.userContentController = userContentController
  37. //加入js-app message
  38. // bbs 回复
  39. userContentController.add(self, name: "ReplyAction")
  40. // 打开工作 {"work":"", "workCompleted":"", "title":""}
  41. userContentController.add(self, name: "openO2Work")
  42. // 4个分类 task taskCompleted read readCompleted
  43. userContentController.add(self, name: "openO2WorkSpace")
  44. // 打开cms appId
  45. userContentController.add(self, name: "openO2CmsApplication")
  46. // 打开cms docId docTitle
  47. userContentController.add(self, name: "openO2CmsDocument")
  48. // 打开meeting
  49. userContentController.add(self, name: "openO2Meeting")
  50. // 打开 calendar
  51. userContentController.add(self, name: "openO2Calendar")
  52. // 打开扫一扫
  53. userContentController.add(self, name: "openScan")
  54. self.webView = WKWebView(frame: self.view.frame, configuration: webViewConfig)
  55. view = webView
  56. }
  57. ///Generates script to create given cookies
  58. public func getJSCookiesString(cookies: [HTTPCookie]) -> String {
  59. var result = ""
  60. let dateFormatter = DateFormatter()
  61. dateFormatter.timeZone = NSTimeZone(abbreviation: "UTC") as TimeZone?
  62. dateFormatter.dateFormat = "EEE, d MMM yyyy HH:mm:ss zzz"
  63. for cookie in cookies {
  64. result += "document.cookie='\(cookie.name)=\(cookie.value); domain=\(cookie.domain); path=\(cookie.path); "
  65. if let date = cookie.expiresDate {
  66. result += "expires=\(dateFormatter.string(from: date)); "
  67. }
  68. if (cookie.isSecure) {
  69. result += "secure; "
  70. }
  71. result += "'; "
  72. }
  73. return result
  74. }
  75. }
  76. extension BaseWebViewUIViewController: WKScriptMessageHandler {
  77. public func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
  78. let name = message.name
  79. switch name {
  80. case "ReplyAction":
  81. DDLogDebug("回复 帖子 message.body = \(message.body)")
  82. let pId : String?
  83. if message.body is NSDictionary {
  84. let parentId:NSDictionary = message.body as! NSDictionary
  85. pId = parentId["body"] as? String
  86. }else if message.body is NSString {
  87. pId = String(message.body as! NSString)
  88. }else {
  89. pId = nil
  90. }
  91. self.performSegue(withIdentifier: "showReplyActionSegue", sender: pId)
  92. break
  93. case "openO2Work":
  94. DDLogDebug("打开工作界面。。。。。")
  95. let body = message.body
  96. if body is NSDictionary {
  97. let dic = body as! NSDictionary
  98. let work = dic["work"] as? String
  99. let workCompleted = dic["workCompleted"] as? String
  100. let title = dic["title"] as? String
  101. self.openWork(work: (work ?? ""), workCompleted: (workCompleted ?? ""), title: (title ?? ""))
  102. }else {
  103. DDLogError("message body 不是一个字典。。。。。。")
  104. }
  105. break
  106. case "openO2WorkSpace":
  107. DDLogDebug("打开工作列表。。。。。")
  108. if message.body is NSString {
  109. let type = message.body as! NSString
  110. self.openO2WorkSpace(type: String(type))
  111. }else {
  112. DDLogError("打开工作列表失败, type不存在!!!!!")
  113. }
  114. break
  115. case "openO2CmsApplication":
  116. DDLogDebug("打开cms栏目。。。。。")
  117. if message.body is NSString {
  118. let appId = message.body as! NSString
  119. self.openCmsApplication(appId: String(appId))
  120. }else if message.body is NSDictionary {
  121. let appBody = message.body as! NSDictionary
  122. if let appId = appBody["appId"] {
  123. self.openCmsApplication(appId: (appId as! String))
  124. }
  125. }else {
  126. DDLogError("打开cms栏目失败, appId不存在!!!!!")
  127. }
  128. break
  129. case "openO2CmsDocument":
  130. DDLogDebug("打开cms 文档。。。。。")
  131. if message.body is NSDictionary {
  132. let appBody = message.body as! NSDictionary
  133. let docId = appBody["docId"] as? String
  134. let docTitle = appBody["docTitle"] as? String
  135. self.openCmsDocument(docId: (docId ?? "" ), docTitle: (docTitle ?? ""))
  136. }else {
  137. DDLogError("打开cms文档失败, 参数不存在!!!!!")
  138. }
  139. break
  140. case "openO2Meeting":
  141. DDLogDebug("打开会议管理。。。。。")
  142. self.openO2Meeting()
  143. break
  144. case "openO2Calendar":
  145. DDLogDebug("打开日程管理。。。。。")
  146. self.openO2Calendar()
  147. break
  148. case "openScan":
  149. self.openScan()
  150. break
  151. default:
  152. break
  153. }
  154. }
  155. private func openWork(work: String, workCompleted: String, title: String) {
  156. let storyBoard = UIStoryboard(name: "task", bundle: nil)
  157. let destVC = storyBoard.instantiateViewController(withIdentifier: "todoTaskDetailVC") as! TodoTaskDetailViewController
  158. let json = """
  159. {"work":"\(work)", "workCompleted":"\(workCompleted)", "title":"\(title)"}
  160. """
  161. let todo = TodoTask(JSONString: json)
  162. destVC.todoTask = todo
  163. destVC.backFlag = 3 //隐藏就行
  164. self.show(destVC, sender: nil)
  165. }
  166. // task taskCompleted read readCompleted
  167. private func openO2WorkSpace(type: String) {
  168. let storyBoard = UIStoryboard(name: "task", bundle: nil)
  169. let destVC = storyBoard.instantiateViewController(withIdentifier: "todoTask")
  170. let nsType = NSString(string: type).lowercased
  171. DDLogDebug("打开工作区, type:\(nsType)")
  172. if "taskcompleted" == nsType {
  173. AppConfigSettings.shared.taskIndex = 2
  174. }else if "read" == nsType {
  175. AppConfigSettings.shared.taskIndex = 1
  176. }else if "readcompleted" == nsType {
  177. AppConfigSettings.shared.taskIndex = 3
  178. }else {
  179. AppConfigSettings.shared.taskIndex = 0
  180. }
  181. self.show(destVC, sender: nil)
  182. }
  183. private func openCmsApplication(appId: String) {
  184. DDLogInfo("打开栏目, appId:\(appId)")
  185. let url = AppDelegate.o2Collect.generateURLWithAppContextKey(CMSContext.cmsContextKey, query: CMSContext.cmsCategoryListQuery, parameter: ["##appId##": appId as AnyObject])
  186. ProgressHUD.show("Loading...", interaction: false)
  187. Alamofire.request(url!, method: .get, parameters: nil, encoding: JSONEncoding.default, headers: nil).responseJSON { (response) in
  188. switch response.result {
  189. case .success(let val):
  190. let categroyList = Mapper<CMSCategoryData>().map(JSONObject: val)
  191. if let count = categroyList?.data?.count {
  192. if count > 0 {
  193. let storyBoard = UIStoryboard(name: "information", bundle: nil)
  194. let destVC = storyBoard.instantiateViewController(withIdentifier: "CMSCategoryListController") as! CMSCategoryListViewController
  195. destVC.title = categroyList?.data?.first?.appName ?? ""
  196. let d = CMSData(JSONString: "{\"id\":\"\"}")
  197. d?.wrapOutCategoryList = categroyList?.data
  198. destVC.cmsData = d
  199. self.show(destVC, sender: nil)
  200. }
  201. }
  202. ProgressHUD.dismiss()
  203. case .failure(let err):
  204. DDLogError(err.localizedDescription)
  205. ProgressHUD.dismiss()
  206. }
  207. }
  208. }
  209. private func openCmsDocument(docId: String, docTitle: String) {
  210. DDLogInfo("打开文档, docId:\(docId) , docTitle:\(docTitle)")
  211. let storyBoard = UIStoryboard(name: "information", bundle: nil)
  212. let destVC = storyBoard.instantiateViewController(withIdentifier: "CMSSubjectDetailVC") as! CMSItemDetailViewController
  213. let json = """
  214. {"title":"\(docTitle)", "id":"\(docId)"}
  215. """
  216. destVC.itemData = CMSCategoryItemData(JSONString: json)
  217. self.show(destVC, sender: nil)
  218. }
  219. private func openO2Meeting() {
  220. let storyBoard = UIStoryboard(name: "meeting", bundle: nil)
  221. if let destVC = storyBoard.instantiateInitialViewController() {
  222. self.show(destVC, sender: nil)
  223. }else {
  224. DDLogError("会议 模块打开失败,没有找到vc")
  225. }
  226. }
  227. private func openO2Calendar() {
  228. let storyBoard = UIStoryboard(name: "calendar", bundle: nil)
  229. if let destVC = storyBoard.instantiateInitialViewController() {
  230. self.show(destVC, sender: nil)
  231. }else {
  232. DDLogError("calendar 模块打开失败,没有找到vc")
  233. }
  234. }
  235. private func openScan() {
  236. if let scanVC = ScanHelper.initScanViewController() {
  237. self.pushVC(scanVC)
  238. }else {
  239. gotoApplicationSettings(alertMessage: "是否跳转到手机设置页面开启相机权限?")
  240. }
  241. }
  242. }