BaseWebViewUIViewController.swift 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329
  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. import JHTAlertController
  15. protocol BaseWebViewUIViewControllerJSDelegate {
  16. func closeUIViewWindow()
  17. func actionBarLoaded(show: Bool)
  18. }
  19. open class BaseWebViewUIViewController: UIViewController {
  20. var webView:WKWebView!
  21. var delegate: BaseWebViewUIViewControllerJSDelegate?
  22. override open func viewDidLoad() {
  23. super.viewDidLoad()
  24. // Do any additional setup after loading the view.
  25. }
  26. override open func didReceiveMemoryWarning() {
  27. super.didReceiveMemoryWarning()
  28. // Dispose of any resources that can be recreated.
  29. }
  30. open func theWebView(){
  31. setupWebView()
  32. }
  33. public func setupWebView() {
  34. let userContentController = WKUserContentController()
  35. //cookie脚本
  36. if let cookies = HTTPCookieStorage.shared.cookies {
  37. let script = getJSCookiesString(cookies: cookies)
  38. let cookieScript = WKUserScript(source: script, injectionTime: WKUserScriptInjectionTime.atDocumentStart, forMainFrameOnly: false)
  39. userContentController.addUserScript(cookieScript)
  40. }
  41. let webViewConfig = WKWebViewConfiguration()
  42. webViewConfig.userContentController = userContentController
  43. //加入js-app message
  44. // bbs 回复
  45. userContentController.add(self, name: "ReplyAction")
  46. // protal已经存在ActionBar
  47. userContentController.add(self, name: "actionBarLoaded")
  48. // 打开工作 {"work":"", "workCompleted":"", "title":""}
  49. userContentController.add(self, name: "openO2Work")
  50. // 4个分类 task taskCompleted read readCompleted
  51. userContentController.add(self, name: "openO2WorkSpace")
  52. // 打开cms appId
  53. userContentController.add(self, name: "openO2CmsApplication")
  54. // 打开cms docId docTitle
  55. userContentController.add(self, name: "openO2CmsDocument")
  56. // 打开meeting
  57. userContentController.add(self, name: "openO2Meeting")
  58. // 打开 calendar
  59. userContentController.add(self, name: "openO2Calendar")
  60. // 打开扫一扫
  61. userContentController.add(self, name: "openScan")
  62. userContentController.add(self, name: "openO2Alert")
  63. // 打开钉钉
  64. userContentController.add(self, name: "openDingtalk")
  65. // 关闭当前UIViewController
  66. userContentController.add(self, name: "closeNativeWindow")
  67. self.webView = WKWebView(frame: self.view.frame, configuration: webViewConfig)
  68. view = webView
  69. }
  70. ///Generates script to create given cookies
  71. public func getJSCookiesString(cookies: [HTTPCookie]) -> String {
  72. var result = ""
  73. let dateFormatter = DateFormatter()
  74. dateFormatter.timeZone = NSTimeZone(abbreviation: "UTC") as TimeZone?
  75. dateFormatter.dateFormat = "EEE, d MMM yyyy HH:mm:ss zzz"
  76. for cookie in cookies {
  77. result += "document.cookie='\(cookie.name)=\(cookie.value); domain=\(cookie.domain); path=\(cookie.path); "
  78. if let date = cookie.expiresDate {
  79. result += "expires=\(dateFormatter.string(from: date)); "
  80. }
  81. if (cookie.isSecure) {
  82. result += "secure; "
  83. }
  84. result += "'; "
  85. }
  86. return result
  87. }
  88. }
  89. extension BaseWebViewUIViewController: WKScriptMessageHandler {
  90. public func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
  91. let name = message.name
  92. switch name {
  93. case "ReplyAction":
  94. DDLogDebug("回复 帖子 message.body = \(message.body)")
  95. let pId : String?
  96. if message.body is NSDictionary {
  97. let parentId:NSDictionary = message.body as! NSDictionary
  98. pId = parentId["body"] as? String
  99. }else if message.body is NSString {
  100. pId = String(message.body as! NSString)
  101. }else {
  102. pId = nil
  103. }
  104. self.performSegue(withIdentifier: "showReplyActionSegue", sender: pId)
  105. break
  106. case "openO2Work":
  107. DDLogDebug("打开工作界面。。。。。")
  108. let body = message.body
  109. if body is NSDictionary {
  110. let dic = body as! NSDictionary
  111. let work = dic["work"] as? String
  112. let workCompleted = dic["workCompleted"] as? String
  113. let title = dic["title"] as? String
  114. self.openWork(work: (work ?? ""), workCompleted: (workCompleted ?? ""), title: (title ?? ""))
  115. }else {
  116. DDLogError("message body 不是一个字典。。。。。。")
  117. }
  118. break
  119. case "openO2WorkSpace":
  120. DDLogDebug("打开工作列表。。。。。")
  121. if message.body is NSString {
  122. let type = message.body as! NSString
  123. self.openO2WorkSpace(type: String(type))
  124. }else {
  125. DDLogError("打开工作列表失败, type不存在!!!!!")
  126. }
  127. break
  128. case "openO2CmsApplication":
  129. DDLogDebug("打开cms栏目。。。。。")
  130. if message.body is NSString {
  131. let appId = message.body as! NSString
  132. self.openCmsApplication(appId: String(appId))
  133. }else if message.body is NSDictionary {
  134. let appBody = message.body as! NSDictionary
  135. if let appId = appBody["appId"] {
  136. self.openCmsApplication(appId: (appId as! String))
  137. }
  138. }else {
  139. DDLogError("打开cms栏目失败, appId不存在!!!!!")
  140. }
  141. break
  142. case "openO2CmsDocument":
  143. DDLogDebug("打开cms 文档。。。。。")
  144. if message.body is NSDictionary {
  145. let appBody = message.body as! NSDictionary
  146. let docId = appBody["docId"] as? String
  147. let docTitle = appBody["docTitle"] as? String
  148. self.openCmsDocument(docId: (docId ?? "" ), docTitle: (docTitle ?? ""))
  149. }else {
  150. DDLogError("打开cms文档失败, 参数不存在!!!!!")
  151. }
  152. break
  153. case "openO2Meeting":
  154. DDLogDebug("打开会议管理。。。。。")
  155. self.openO2Meeting()
  156. break
  157. case "openO2Calendar":
  158. DDLogDebug("打开日程管理。。。。。")
  159. self.openO2Calendar()
  160. break
  161. case "openScan":
  162. self.openScan()
  163. break
  164. case "openO2Alert":
  165. if message.body is NSString {
  166. let msg = message.body as! NSString
  167. self.openO2Alert(message: String(msg))
  168. }
  169. break
  170. case "closeNativeWindow":
  171. DDLogDebug("关闭窗口!!!!")
  172. self.delegate?.closeUIViewWindow()
  173. break
  174. case "openDingtalk":
  175. self.openDingtalk()
  176. break
  177. case "actionBarLoaded":
  178. self.delegate?.actionBarLoaded(show: true)
  179. break
  180. default:
  181. break
  182. }
  183. }
  184. private func openO2Alert(message: String) {
  185. DDLogDebug("O2 alert msg:\(message)")
  186. let alertController = JHTAlertController(title: "", message: message, preferredStyle: .alert)
  187. alertController.titleImage = #imageLiteral(resourceName: "logo80-bai")
  188. alertController.messageTextColor = UIColor(hex: "#030303")
  189. alertController.titleViewBackgroundColor = UIColor.hexInt(0xFB4747)
  190. alertController.alertBackgroundColor = UIColor(hexString: "#FCFCFC", alpha: 0.9)!
  191. alertController.setAllButtonBackgroundColors(to: UIColor(hexString: "#FCFCFC", alpha: 0.9)!)
  192. alertController.setButtonTextColorFor(.default, to: UIColor(hex: "#FB4747"))
  193. alertController.setButtonTextColorFor(.cancel, to: UIColor(hex: "#FB4747"))
  194. alertController.hasRoundedCorners = true
  195. let okAction = JHTAlertAction(title: "确定", style: .default, handler: {action in
  196. })
  197. alertController.addActions([okAction])
  198. present(alertController, animated: true, completion: nil)
  199. }
  200. private func openWork(work: String, workCompleted: String, title: String) {
  201. let storyBoard = UIStoryboard(name: "task", bundle: nil)
  202. let destVC = storyBoard.instantiateViewController(withIdentifier: "todoTaskDetailVC") as! TodoTaskDetailViewController
  203. let json = """
  204. {"work":"\(work)", "workCompleted":"\(workCompleted)", "title":"\(title)"}
  205. """
  206. DDLogDebug("openWork json: \(json)")
  207. let todo = TodoTask(JSONString: json)
  208. destVC.todoTask = todo
  209. destVC.backFlag = 3 //隐藏就行
  210. self.show(destVC, sender: nil)
  211. }
  212. // task taskCompleted read readCompleted
  213. private func openO2WorkSpace(type: String) {
  214. let storyBoard = UIStoryboard(name: "task", bundle: nil)
  215. let destVC = storyBoard.instantiateViewController(withIdentifier: "todoTask")
  216. let nsType = NSString(string: type).lowercased
  217. DDLogDebug("打开工作区, type:\(nsType)")
  218. if "taskcompleted" == nsType {
  219. AppConfigSettings.shared.taskIndex = 2
  220. }else if "read" == nsType {
  221. AppConfigSettings.shared.taskIndex = 1
  222. }else if "readcompleted" == nsType {
  223. AppConfigSettings.shared.taskIndex = 3
  224. }else {
  225. AppConfigSettings.shared.taskIndex = 0
  226. }
  227. self.show(destVC, sender: nil)
  228. }
  229. private func openCmsApplication(appId: String) {
  230. DDLogInfo("打开栏目, appId:\(appId)")
  231. let url = AppDelegate.o2Collect.generateURLWithAppContextKey(CMSContext.cmsContextKey, query: CMSContext.cmsCategoryListQuery, parameter: ["##appId##": appId as AnyObject])
  232. self.showMessage(title: "Loading...")
  233. Alamofire.request(url!, method: .get, parameters: nil, encoding: JSONEncoding.default, headers: nil).responseJSON { (response) in
  234. switch response.result {
  235. case .success(let val):
  236. let categroyList = Mapper<CMSCategoryData>().map(JSONObject: val)
  237. if let count = categroyList?.data?.count {
  238. if count > 0 {
  239. let storyBoard = UIStoryboard(name: "information", bundle: nil)
  240. let destVC = storyBoard.instantiateViewController(withIdentifier: "CMSCategoryListController") as! CMSCategoryListViewController
  241. destVC.title = categroyList?.data?.first?.appName ?? ""
  242. let d = CMSData(JSONString: "{\"id\":\"\"}")
  243. d?.wrapOutCategoryList = categroyList?.data
  244. destVC.cmsData = d
  245. self.show(destVC, sender: nil)
  246. }
  247. }
  248. self.dismissProgressHUD()
  249. case .failure(let err):
  250. DDLogError(err.localizedDescription)
  251. self.dismissProgressHUD()
  252. }
  253. }
  254. }
  255. private func openCmsDocument(docId: String, docTitle: String) {
  256. DDLogInfo("打开文档, docId:\(docId) , docTitle:\(docTitle)")
  257. let storyBoard = UIStoryboard(name: "information", bundle: nil)
  258. let destVC = storyBoard.instantiateViewController(withIdentifier: "CMSSubjectDetailVC") as! CMSItemDetailViewController
  259. let json = """
  260. {"title":"\(docTitle)", "id":"\(docId)"}
  261. """
  262. destVC.itemData = CMSCategoryItemData(JSONString: json)
  263. self.show(destVC, sender: nil)
  264. }
  265. private func openO2Meeting() {
  266. let storyBoard = UIStoryboard(name: "meeting", bundle: nil)
  267. if let destVC = storyBoard.instantiateInitialViewController() {
  268. self.show(destVC, sender: nil)
  269. }else {
  270. DDLogError("会议 模块打开失败,没有找到vc")
  271. }
  272. }
  273. private func openO2Calendar() {
  274. let storyBoard = UIStoryboard(name: "calendar", bundle: nil)
  275. if let destVC = storyBoard.instantiateInitialViewController() {
  276. self.show(destVC, sender: nil)
  277. }else {
  278. DDLogError("calendar 模块打开失败,没有找到vc")
  279. }
  280. }
  281. private func openScan() {
  282. if let scanVC = ScanHelper.initScanViewController() {
  283. self.pushVC(scanVC)
  284. }else {
  285. gotoApplicationSettings(alertMessage: "是否跳转到手机设置页面开启相机权限?")
  286. }
  287. }
  288. private func openDingtalk() {
  289. UIApplication.shared.open(URL(string: "dingtalk://dingtalkclient/")!, options: [:]) { (result) in
  290. DDLogInfo("打开了钉钉。。。。\(result)")
  291. }
  292. }
  293. }