BaseTaskWebViewController.swift 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639
  1. //
  2. // BaseTaskWebViewController.swift
  3. // O2Platform
  4. //
  5. // Created by 刘振兴 on 2017/3/13.
  6. // Copyright © 2017年 zoneland. All rights reserved.
  7. //
  8. import UIKit
  9. import WebKit
  10. import Alamofire
  11. import AlamofireObjectMapper
  12. import SwiftyJSON
  13. import QuickLook
  14. import ObjectMapper
  15. import BSImagePicker
  16. import Photos
  17. import CocoaLumberjack
  18. import JHTAlertController
  19. import O2OA_Auth_SDK
  20. enum TaskAttachmentOperationType {
  21. case upload(String)
  22. case download(String,String)
  23. case replace(String)
  24. }
  25. protocol O2WorkFormLoadedDelegate {
  26. func workFormLoaded()
  27. }
  28. class BaseTaskWebViewController: UIViewController {
  29. var qlController = TaskAttachmentPreviewController()
  30. //是否是已办
  31. open var isWorkCompeleted:Bool = false
  32. open var workId:String?
  33. var loadedDelegate: O2WorkFormLoadedDelegate?
  34. var webView:WKWebView!
  35. override open func viewDidLoad() {
  36. super.viewDidLoad()
  37. qlController.dataSource = qlController
  38. qlController.delegate = qlController
  39. // Do any additional setup after loading the view.
  40. }
  41. deinit {
  42. }
  43. override open func didReceiveMemoryWarning() {
  44. super.didReceiveMemoryWarning()
  45. // Dispose of any resources that can be recreated.
  46. }
  47. open func theWebView(){
  48. setupWebView()
  49. }
  50. public func setupWebView() {
  51. let userContentController = WKUserContentController()
  52. //cookie脚本
  53. if let cookies = HTTPCookieStorage.shared.cookies {
  54. let script = getJSCookiesString(cookies: cookies)
  55. let cookieScript = WKUserScript(source: script, injectionTime: WKUserScriptInjectionTime.atDocumentStart, forMainFrameOnly: false)
  56. userContentController.addUserScript(cookieScript)
  57. }
  58. let webViewConfig = WKWebViewConfiguration()
  59. webViewConfig.userContentController = userContentController
  60. //加入js-app message appFormLoaded
  61. userContentController.add(self, name: "appFormLoaded")
  62. userContentController.add(self, name: "uploadAttachment")
  63. userContentController.add(self, name: "downloadAttachment")
  64. userContentController.add(self, name: "replaceAttachment")
  65. userContentController.add(self, name: "openO2Alert")
  66. userContentController.add(self, name: "openDocument")
  67. userContentController.add(self, name: "uploadImage2FileStorage")
  68. userContentController.add(self, name: "o2mNotificationAlert")
  69. userContentController.add(self, name: "o2mLog")
  70. userContentController.add(O2JsApiNotification(), name: "o2mNotification")
  71. self.webView = WKWebView(frame: self.view.frame, configuration: webViewConfig)
  72. }
  73. //上传附件
  74. open func uploadAttachment(_ site:String){
  75. //选择附件上传
  76. let updloadURL = AppDelegate.o2Collect.generateURLWithAppContextKey(TaskContext.taskContextKey, query: TaskContext.todoTaskUploadAttachmentQuery, parameter: ["##workId##":workId as AnyObject])
  77. self.uploadAttachment(site, uploadURL: updloadURL!)
  78. //回调layout.appForm.uploadedAttachment(site, attachmentId)
  79. }
  80. private func uploadAttachment(_ site:String,uploadURL url:String){
  81. let vc = FileBSImagePickerViewController()
  82. bs_presentImagePickerController(vc, animated: true,
  83. select: { (asset: PHAsset) -> Void in
  84. // User selected an asset.
  85. // Do something with it, start upload perhaps?
  86. }, deselect: { (asset: PHAsset) -> Void in
  87. // User deselected an assets.
  88. // Do something, cancel upload?
  89. }, cancel: { (assets: [PHAsset]) -> Void in
  90. // User cancelled. And this where the assets currently selected.
  91. }, finish: { (assets: [PHAsset]) -> Void in
  92. for asset in assets {
  93. switch asset.mediaType {
  94. case .audio:
  95. DDLogDebug("Audio")
  96. case .image:
  97. let options = PHImageRequestOptions()
  98. options.isSynchronous = true
  99. options.deliveryMode = .fastFormat
  100. options.resizeMode = .none
  101. PHImageManager.default().requestImageData(for: asset, options: options, resultHandler: { (imageData, result, imageOrientation, dict) in
  102. //DDLogDebug("result = \(result) imageOrientation = \(imageOrientation) \(dict)")
  103. let fileURL = dict?["PHImageFileURLKey"] as! URL
  104. DispatchQueue.main.async {
  105. self.showMessage(title: "上传中...")
  106. }
  107. DispatchQueue.global(qos: .userInitiated).async {
  108. Alamofire.upload(multipartFormData: { (mData) in
  109. //mData.append(fileURL, withName: "file")
  110. mData.append(imageData!, withName: "file", fileName: fileURL.lastPathComponent, mimeType: "application/octet-stream")
  111. let siteData = site.data(using: String.Encoding.utf8, allowLossyConversion: false)
  112. mData.append(siteData!, withName: "site")
  113. }, to: url, encodingCompletion: { (encodingResult) in
  114. switch encodingResult {
  115. case .success(let upload, _, _):
  116. debugPrint(upload)
  117. upload.responseJSON {
  118. respJSON in
  119. switch respJSON.result {
  120. case .success(let val):
  121. let attachId = JSON(val)["data"]["id"].string!
  122. DispatchQueue.main.async {
  123. //ProgressHUD.showSuccess("上传成功")
  124. let callJS = "layout.appForm.uploadedAttachment(\"\(site)\", \"\(attachId)\")"
  125. self.webView.evaluateJavaScript(callJS, completionHandler: { (result, err) in
  126. self.showSuccess(title: "上传成功")
  127. })
  128. }
  129. case .failure(let err):
  130. DispatchQueue.main.async {
  131. DDLogError(err.localizedDescription)
  132. self.showError(title: "上传失败")
  133. }
  134. break
  135. }
  136. }
  137. case .failure(let errType):
  138. DispatchQueue.main.async {
  139. DDLogError(errType.localizedDescription)
  140. self.showError(title: "上传失败")
  141. }
  142. }
  143. })
  144. }
  145. })
  146. case .video:
  147. let options = PHVideoRequestOptions()
  148. options.deliveryMode = .fastFormat
  149. options.isNetworkAccessAllowed = true
  150. options.progressHandler = { (progress,err, stop,dict) in
  151. DDLogDebug("progress = \(progress) dict = \(dict)")
  152. }
  153. PHImageManager.default().requestAVAsset(forVideo: asset, options: options, resultHandler: { (avAsset, avAudioMx, dict) in
  154. })
  155. case .unknown:
  156. DDLogDebug("Unknown")
  157. }
  158. }
  159. }, completion: nil)
  160. }
  161. //下载预览附件
  162. open func downloadAttachment(_ attachmentId:String){
  163. //生成两个URL,一个获取附件信息,一个链接正式下载
  164. var infoURL:String?,downURL:String?
  165. if isWorkCompeleted {
  166. infoURL = AppDelegate.o2Collect.generateURLWithAppContextKey(TaskedContext.taskedContextKey, query: TaskedContext.taskedGetAttachmentInfoQuery, parameter: ["##attachmentId##":attachmentId as AnyObject,"##workcompletedId##":workId as AnyObject])
  167. downURL = AppDelegate.o2Collect.generateURLWithAppContextKey(TaskedContext.taskedContextKey, query: TaskedContext.taskedGetAttachmentQuery, parameter:["##attachmentId##":attachmentId as AnyObject,"##workcompletedId##":workId as AnyObject])
  168. }else{
  169. infoURL = AppDelegate.o2Collect.generateURLWithAppContextKey(TaskContext.taskContextKey, query: TaskContext.todoTaskGetAttachmentInfoQuery, parameter: ["##attachmentId##":attachmentId as AnyObject,"##workId##":workId as AnyObject])
  170. downURL = AppDelegate.o2Collect.generateURLWithAppContextKey(TaskContext.taskContextKey, query: TaskContext.todoTaskGetAttachmentQuery, parameter:["##attachmentId##":attachmentId as AnyObject,"##workId##":workId as AnyObject])
  171. }
  172. self.showAttachViewInController(infoURL!, downURL!)
  173. }
  174. //替换附件
  175. open func replaceAttachment(_ attachmentId:String, _ site:String){
  176. //替换结束后回调js名称
  177. let replaceURL = AppDelegate.o2Collect.generateURLWithAppContextKey(TaskContext.taskContextKey, query: TaskContext.todoTaskUpReplaceAttachmentQuery, parameter: ["##attachmentId##":attachmentId as AnyObject,"##workId##":workId as AnyObject])!
  178. self.replaceAttachment(site, attachmentId, replaceURL: replaceURL)
  179. //layout.appForm.replacedAttachment(site , attachmentId)
  180. }
  181. /**
  182. * 下载公文 并阅览
  183. **/
  184. open func downloadDocumentAndPreview(_ url: String) {
  185. DDLogDebug("文档下载地址:\(url)")
  186. self.showMessage(title: "下载中...")
  187. // 文件地址
  188. let localFileDestination: DownloadRequest.DownloadFileDestination = { _, response in
  189. let documentsURL = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask)[0]
  190. let fileURL = documentsURL.appendingPathComponent(response.suggestedFilename!)
  191. // 有重名文件就删除重建
  192. return (fileURL, [.removePreviousFile, .createIntermediateDirectories])
  193. }
  194. Alamofire.download(url, to: localFileDestination).response(completionHandler: { (response) in
  195. if response.error == nil , let fileurl = response.destinationURL?.path {
  196. DDLogDebug("文件地址:\(fileurl)")
  197. //打开文件
  198. self.dismissProgressHUD()
  199. self.previewAttachment(fileurl)
  200. }else{
  201. let msg = response.error?.localizedDescription ?? ""
  202. DDLogError("下载文件出错,\(msg)")
  203. DispatchQueue.main.async {
  204. self.showError(title: "预览文件出错")
  205. }
  206. }
  207. })
  208. }
  209. private func replaceAttachment(_ site:String,_ attachmentId:String,replaceURL url:String){
  210. let vc = FileBSImagePickerViewController()
  211. bs_presentImagePickerController(vc, animated: true,
  212. select: { (asset: PHAsset) -> Void in
  213. // User selected an asset.
  214. // Do something with it, start upload perhaps?
  215. }, deselect: { (asset: PHAsset) -> Void in
  216. // User deselected an assets.
  217. // Do something, cancel upload?
  218. }, cancel: { (assets: [PHAsset]) -> Void in
  219. // User cancelled. And this where the assets currently selected.
  220. }, finish: { (assets: [PHAsset]) -> Void in
  221. for asset in assets {
  222. switch asset.mediaType {
  223. case .audio:
  224. DDLogDebug("Audio")
  225. case .image:
  226. let options = PHImageRequestOptions()
  227. options.isSynchronous = true
  228. options.deliveryMode = .fastFormat
  229. options.resizeMode = .none
  230. PHImageManager.default().requestImageData(for: asset, options: options, resultHandler: { (imageData, result, imageOrientation, dict) in
  231. //DDLogDebug("result = \(result) imageOrientation = \(imageOrientation) \(dict)")
  232. let fileURL = dict?["PHImageFileURLKey"] as! URL
  233. DispatchQueue.main.async {
  234. self.showMessage(title: "上传中...")
  235. }
  236. DispatchQueue.global(qos: .userInitiated).async {
  237. Alamofire.upload(multipartFormData: { (mData) in
  238. //mData.append(fileURL, withName: "file")
  239. mData.append(imageData!, withName: "file", fileName: fileURL.lastPathComponent, mimeType: "application/octet-stream")
  240. let siteData = site.data(using: String.Encoding.utf8, allowLossyConversion: false)
  241. mData.append(siteData!, withName: "site")
  242. }, usingThreshold: SessionManager.multipartFormDataEncodingMemoryThreshold, to: url, method: .put, headers: nil, encodingCompletion: { (encodingResult) in
  243. switch encodingResult {
  244. case .success(let upload, _, _):
  245. debugPrint(upload)
  246. upload.responseJSON {
  247. respJSON in
  248. switch respJSON.result {
  249. case .success( _):
  250. //let attachId = JSON(val)["data"]["id"].string!
  251. DispatchQueue.main.async {
  252. //ProgressHUD.showSuccess("上传成功")
  253. let callJS = "layout.appForm.replacedAttachment(\"\(site)\", \"\(attachmentId)\")"
  254. self.webView.evaluateJavaScript(callJS, completionHandler: { (result, err) in
  255. self.showSuccess(title: "替换成功")
  256. })
  257. }
  258. case .failure(let err):
  259. DispatchQueue.main.async {
  260. DDLogError(err.localizedDescription)
  261. self.showError(title: "替换失败")
  262. }
  263. break
  264. }
  265. }
  266. case .failure(let errType):
  267. DispatchQueue.main.async {
  268. DDLogError(errType.localizedDescription)
  269. self.showError(title: "替换失败")
  270. }
  271. }
  272. })
  273. }
  274. })
  275. case .video:
  276. let options = PHVideoRequestOptions()
  277. options.deliveryMode = .fastFormat
  278. options.isNetworkAccessAllowed = true
  279. options.progressHandler = { (progress,err, stop,dict) in
  280. DDLogDebug("progress = \(progress) dict = \(String(describing: dict))")
  281. }
  282. PHImageManager.default().requestAVAsset(forVideo: asset, options: options, resultHandler: { (avAsset, avAudioMx, dict) in
  283. })
  284. case .unknown:
  285. DDLogDebug("Unknown")
  286. }
  287. }
  288. }, completion: nil)
  289. }
  290. fileprivate func showAttachViewInController(_ infoURL:String,_ downURL:String){
  291. self.showMessage(title: "下载中...")
  292. Alamofire.request(infoURL).responseJSON { (response) in
  293. switch response.result {
  294. case .success(let val):
  295. //DDLogDebug(JSON(val).description)
  296. let info = Mapper<O2TaskAttachmentInfo>().map(JSONString: JSON(val).description)
  297. //执行下载
  298. let destination: DownloadRequest.DownloadFileDestination = { _, _ in
  299. let documentsURL = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask)[0]
  300. let fileURL = documentsURL.appendingPathComponent((info?.data?.name)!)
  301. return (fileURL, [.removePreviousFile, .createIntermediateDirectories])
  302. }
  303. Alamofire.download(downURL, to: destination).response(completionHandler: { (response) in
  304. if response.error == nil , let fileurl = response.destinationURL?.path {
  305. //打开文件
  306. self.dismissProgressHUD()
  307. self.previewAttachment(fileurl)
  308. }else{
  309. DispatchQueue.main.async {
  310. self.showError(title: "预览文件出错")
  311. }
  312. }
  313. })
  314. break
  315. case .failure(let err):
  316. DDLogError(err.localizedDescription)
  317. DispatchQueue.main.async {
  318. self.showError(title: "预览文件出错")
  319. }
  320. break
  321. }
  322. }
  323. }
  324. private func previewAttachment(_ url:String){
  325. let currentURL = NSURL(fileURLWithPath: url)
  326. if QLPreviewController.canPreview(currentURL) {
  327. qlController.currentFileURLS.removeAll(keepingCapacity: true)
  328. qlController.currentFileURLS.append(currentURL)
  329. qlController.reloadData()
  330. if #available(iOS 10, *) {
  331. let navVC = ZLNormalNavViewController(rootViewController: qlController)
  332. qlController.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .plain, target: qlController, action: #selector(qlController.qlCloseWindow))
  333. self.presentVC(navVC)
  334. }else{
  335. //if #available(iOS 9, *){
  336. self.pushVC(qlController)
  337. //}
  338. }
  339. }else{
  340. self.showError(title: "此文件无法预览,请在PC端查看")
  341. }
  342. }
  343. private func openO2Alert(message: String) {
  344. DDLogDebug("O2 alert msg:\(message)")
  345. let alertController = JHTAlertController(title: "", message: message, preferredStyle: .alert)
  346. alertController.titleImage = #imageLiteral(resourceName: "logo80-bai")
  347. alertController.messageTextColor = UIColor(hex: "#030303")
  348. alertController.titleViewBackgroundColor = UIColor.hexInt(0xFB4747)
  349. alertController.alertBackgroundColor = UIColor(hexString: "#FCFCFC", alpha: 0.9)!
  350. alertController.setAllButtonBackgroundColors(to: UIColor(hexString: "#FCFCFC", alpha: 0.9)!)
  351. alertController.setButtonTextColorFor(.default, to: UIColor(hex: "#FB4747"))
  352. alertController.setButtonTextColorFor(.cancel, to: UIColor(hex: "#FB4747"))
  353. alertController.hasRoundedCorners = true
  354. let okAction = JHTAlertAction(title: "确定", style: .default, handler: {action in
  355. })
  356. alertController.addActions([okAction])
  357. present(alertController, animated: true, completion: nil)
  358. }
  359. private func downloadFile(_ attachmentId:String,_ completed:@escaping (_ localURLForFile:String) -> Void){
  360. }
  361. ///Generates script to create given cookies
  362. public func getJSCookiesString(cookies: [HTTPCookie]) -> String {
  363. var result = ""
  364. let dateFormatter = DateFormatter()
  365. dateFormatter.timeZone = NSTimeZone(abbreviation: "UTC") as TimeZone!
  366. dateFormatter.dateFormat = "EEE, d MMM yyyy HH:mm:ss zzz"
  367. for cookie in cookies {
  368. result += "document.cookie='\(cookie.name)=\(cookie.value); domain=\(cookie.domain); path=\(cookie.path); "
  369. if let date = cookie.expiresDate {
  370. result += "expires=\(dateFormatter.string(from: date)); "
  371. }
  372. if (cookie.isSecure) {
  373. result += "secure; "
  374. }
  375. result += "'; "
  376. }
  377. return result
  378. }
  379. // 表单图片控件
  380. private func uploadImage(data: O2WebViewUploadImage) {
  381. if data.callback == nil || data.callback.isEmpty || data.reference == nil || data.reference.isEmpty
  382. || data.referencetype == nil || data.referencetype.isEmpty {
  383. self.showError(title: "参数传入为空,无法上传图片")
  384. return
  385. }
  386. data.scale = 800
  387. let chooseImage = FileBSImagePickerViewController()
  388. self.bs_presentImagePickerController(chooseImage, animated: true, select: nil, deselect: nil, cancel: nil, finish: { (arr) in
  389. let count = arr.count
  390. DDLogDebug("选择了照片数量:\(count)")
  391. if count > 0 {
  392. //获取照片
  393. let asset = arr[0]
  394. if asset.mediaType == .image {
  395. let options = PHImageRequestOptions()
  396. options.isSynchronous = true
  397. options.deliveryMode = .fastFormat
  398. options.resizeMode = .none
  399. PHImageManager.default().requestImageData(for: asset, options: options, resultHandler: { (imageData, result, imageOrientation, dict) in
  400. DispatchQueue.main.async {
  401. self.showMessage(title: "上传中...")
  402. }
  403. var newData = imageData
  404. //处理图片旋转的问题
  405. if imageOrientation != UIImage.Orientation.up && imageData != nil {
  406. let newImage = UIImage(data: imageData!)?.fixOrientation()
  407. if newImage != nil {
  408. newData = newImage?.pngData()
  409. }
  410. }
  411. let fileUploadURL = AppDelegate.o2Collect
  412. .generateURLWithAppContextKey(
  413. FileContext.fileContextKey,
  414. query: FileContext.fileUploadReference,
  415. parameter: [
  416. "##referencetype##": data.referencetype as AnyObject,
  417. "##reference##": data.reference as AnyObject,
  418. "##scale##": String(data.scale) as AnyObject
  419. ],
  420. coverted: true)!
  421. DDLogDebug(fileUploadURL)
  422. let headers:HTTPHeaders = ["x-token":(O2AuthSDK.shared.myInfo()?.token!)!]
  423. let fileURL = dict?["PHImageFileURLKey"] as! URL
  424. DispatchQueue.global(qos: .userInitiated).async {
  425. Alamofire.upload(multipartFormData: { (mData) in
  426. mData.append(newData!, withName: "file", fileName: fileURL.lastPathComponent, mimeType: "image/png")
  427. }, to: fileUploadURL, method: .put, headers: headers, encodingCompletion: { (encodingResult) in
  428. switch encodingResult {
  429. case .success(let upload, _, _):
  430. upload.responseJSON {
  431. respJSON in
  432. switch respJSON.result {
  433. case .success(let val):
  434. let attachId = JSON(val)["data"]["id"].string!
  435. data.fileId = attachId
  436. let callback = data.callback!
  437. let callbackParameterJson = data.toJSONString()
  438. if callbackParameterJson != nil {
  439. DDLogDebug("json:\(callbackParameterJson!)")
  440. DispatchQueue.main.async {
  441. let callJS = "\(callback)('\(callbackParameterJson!)')"
  442. DDLogDebug("执行js:\(callJS)")
  443. self.webView.evaluateJavaScript(callJS, completionHandler: { (result, err) in
  444. self.showSuccess(title: "上传成功")
  445. })
  446. }
  447. }
  448. case .failure(let err):
  449. DispatchQueue.main.async {
  450. DDLogError(err.localizedDescription)
  451. self.showError(title: "上传图片失败")
  452. }
  453. break
  454. }
  455. }
  456. case .failure(let errType):
  457. DispatchQueue.main.async {
  458. DDLogError(errType.localizedDescription)
  459. self.showError(title: "上传图片失败")
  460. }
  461. }
  462. })
  463. }
  464. })
  465. }else {
  466. DDLogError("选择类型不正确,不是照片")
  467. }
  468. }
  469. }, completion: nil)
  470. }
  471. }
  472. extension BaseTaskWebViewController:WKScriptMessageHandler{
  473. func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
  474. let name = message.name
  475. switch name {
  476. case "appFormLoaded":
  477. self.loadedDelegate?.workFormLoaded()
  478. break
  479. case "uploadAttachment":
  480. ZonePermissions.requestImagePickerAuthorization(callback: { (zoneStatus) in
  481. if zoneStatus == ZoneAuthorizationStatus.zAuthorizationStatusAuthorized {
  482. let site = (message.body as! NSDictionary)["site"]
  483. self.uploadAttachment(site as! String)
  484. }else {
  485. //显示
  486. let alertController = UIAlertController(title: "上传提示", message: "请设置照片允许访问权限", preferredStyle: UIAlertController.Style.alert)
  487. alertController.addAction(UIAlertAction(title: "去设置", style: .destructive, handler: { (action) in
  488. let setURL = URL(string: UIApplication.openSettingsURLString)!
  489. if UIApplication.shared.canOpenURL(setURL) {
  490. UIApplication.shared.openURL(setURL)
  491. }
  492. }))
  493. alertController.addAction(UIAlertAction(title: "取消", style: .cancel, handler: { (action) in
  494. }))
  495. self.presentVC(alertController)
  496. }
  497. })
  498. break
  499. case "downloadAttachment":
  500. let attachmentId = (message.body as! NSDictionary)["id"]
  501. self.downloadAttachment(attachmentId as! String)
  502. break
  503. case "replaceAttachment":
  504. let attachmentId = (message.body as! NSDictionary)["id"] as! String
  505. let site = (message.body as! NSDictionary)["site"] as? String
  506. self.replaceAttachment(attachmentId, site ?? "")
  507. break
  508. case "openDocument":
  509. let url = (message.body as! NSString)
  510. self.downloadDocumentAndPreview(String(url))
  511. break
  512. case "openO2Alert":
  513. if message.body is NSString {
  514. let msg = message.body as! NSString
  515. self.openO2Alert(message: String(msg))
  516. }
  517. break
  518. case "uploadImage2FileStorage":
  519. DDLogDebug("这里进入了上传图片控件。。。。。。。。。。。。。。。")
  520. if message.body is NSString {
  521. let json = message.body as! NSString
  522. DDLogDebug("上传图片:\(json)")
  523. if let uploadImage = O2WebViewUploadImage.deserialize(from: String(json)) {
  524. self.uploadImage(data: uploadImage)
  525. }else {
  526. DDLogError("解析json失败")
  527. self.showError(title: "参数不正确!")
  528. }
  529. }else {
  530. DDLogError("传入参数类型不正确!")
  531. self.showError(title: "参数不正确!")
  532. }
  533. break
  534. case "o2mNotificationAlert":
  535. if message.body is NSString {
  536. let json = message.body as! NSString
  537. DDLogDebug("alert:\(json)")
  538. if let alert = O2NotificationMessage<O2NotificationAlertMessage>.deserialize(from: String(json)) {
  539. var buttonName = alert.data?.buttonName ?? ""
  540. if buttonName == "" {
  541. buttonName = "确定"
  542. }
  543. let title = alert.data?.title ?? ""
  544. let message = alert.data?.message ?? "消息"
  545. self.showSystemAlertWithButtonName(title: title, message: message , buttonName: buttonName) { (action) in
  546. if alert.callback != nil {
  547. let callJs = "\(alert.callback!)()"
  548. DDLogDebug(callJs)
  549. self.webView.evaluateJavaScript(callJs, completionHandler: { (result, err) in
  550. })
  551. }
  552. }
  553. }else {
  554. DDLogError("解析json失败")
  555. self.showError(title: "参数不正确!")
  556. }
  557. }
  558. break
  559. case "o2mLog":
  560. if message.body is NSString {
  561. let log = message.body as! NSString
  562. DDLogDebug("console.log: "+String(log))
  563. }
  564. break;
  565. default:
  566. DDLogError("未知方法名:\(name)!")
  567. break
  568. }
  569. }
  570. }