CMSItemDetailViewController.swift 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590
  1. //
  2. // CMSItemDetailViewController.swift
  3. // O2Platform
  4. //
  5. // Created by 刘振兴 on 2016/12/9.
  6. // Copyright © 2016年 zoneland. All rights reserved.
  7. //
  8. import UIKit
  9. import WebKit
  10. import Alamofire
  11. import AlamofireObjectMapper
  12. import SwiftyJSON
  13. import ObjectMapper
  14. import QuickLook
  15. import Photos
  16. import CocoaLumberjack
  17. class CMSItemDetailViewController: BaseWebViewUIViewController {
  18. private let qlController = TaskAttachmentPreviewController()
  19. fileprivate var currentFileURLS:[NSURL] = []
  20. var itemData:CMSCategoryItemData? {
  21. didSet {
  22. title = itemData?.title
  23. itemUrl = AppDelegate.o2Collect.genrateURLWithWebContextKey(DesktopContext.DesktopContextKey, query: DesktopContext.cmsItemDetailQuery, parameter: ["##documentId##":itemData?.id as AnyObject])!
  24. }
  25. }
  26. var documentId:String?{
  27. didSet {
  28. itemUrl = AppDelegate.o2Collect.genrateURLWithWebContextKey(DesktopContext.DesktopContextKey, query: DesktopContext.cmsItemDetailQuery, parameter: ["##documentId##":documentId as AnyObject])!
  29. }
  30. }
  31. var itemUrl = ""
  32. var fromCreateDocVC = false
  33. //cms操作control
  34. var myControl: [String : AnyObject]?
  35. //cms底部操作按钮 toolbar
  36. var toolbarView: UIToolbar!
  37. //webview的容器
  38. @IBOutlet weak var webViewContainer: UIView!
  39. @IBOutlet weak var progressView: UIProgressView!
  40. override func viewWillAppear(_ animated: Bool) {
  41. super.viewWillAppear(animated)
  42. //监控进度
  43. webView.addObserver(self, forKeyPath: "estimatedProgress", options: .new, context: nil)
  44. }
  45. override func viewWillDisappear(_ animated: Bool) {
  46. super.viewWillDisappear(animated)
  47. webView.removeObserver(self, forKeyPath: "estimatedProgress")
  48. }
  49. override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
  50. if keyPath == "estimatedProgress" {
  51. progressView.isHidden = webView.estimatedProgress == 1
  52. progressView.setProgress(Float(webView.estimatedProgress), animated: true)
  53. }
  54. }
  55. override func viewDidLoad() {
  56. super.viewDidLoad()
  57. //自定义返回按钮
  58. self.navigationItem.hidesBackButton = true
  59. self.navigationItem.leftBarButtonItem = UIBarButtonItem(image: UIImage(named: "icon_fanhui"), style: .plain, target: self, action: #selector(goBack))
  60. self.navigationItem.leftItemsSupplementBackButton = true
  61. // 底部操作按钮toolbar
  62. self.toolbarView = UIToolbar(frame: CGRect(x: 0, y: self.view.height - 44, width: self.view.width, height: 44))
  63. self.automaticallyAdjustsScrollViewInsets = false
  64. //先添加js注入
  65. addScriptMessageHandler(key: "cmsFormLoaded", handler: self)
  66. addScriptMessageHandler(key: "uploadAttachment", handler: self)
  67. addScriptMessageHandler(key: "downloadAttachment", handler: self)
  68. addScriptMessageHandler(key: "replaceAttachment", handler: self)
  69. addScriptMessageHandler(key: "openDocument", handler: self)
  70. addScriptMessageHandler(key: "closeDocumentWindow", handler: self)
  71. self.theWebView()
  72. self.qlInit()
  73. }
  74. override func didReceiveMemoryWarning() {
  75. super.didReceiveMemoryWarning()
  76. // Dispose of any resources that can be recreated.
  77. }
  78. override func theWebView(){
  79. super.theWebView()
  80. self.webViewContainer.addSubview(self.webView)
  81. self.webView.translatesAutoresizingMaskIntoConstraints = false
  82. let top = NSLayoutConstraint(item: self.webView as Any, attribute: NSLayoutConstraint.Attribute.top, relatedBy: NSLayoutConstraint.Relation.equal, toItem: self.webViewContainer, attribute: NSLayoutConstraint.Attribute.top, multiplier: 1, constant: 0)
  83. let bottom = NSLayoutConstraint(item: self.webView as Any, attribute: NSLayoutConstraint.Attribute.bottom, relatedBy: NSLayoutConstraint.Relation.equal, toItem: self.webViewContainer, attribute: NSLayoutConstraint.Attribute.bottom, multiplier: 1, constant: 0)
  84. let trailing = NSLayoutConstraint(item: self.webView as Any, attribute: NSLayoutConstraint.Attribute.trailing, relatedBy: NSLayoutConstraint.Relation.equal, toItem: self.webViewContainer, attribute: NSLayoutConstraint.Attribute.trailing, multiplier: 1, constant: 0)
  85. let leading = NSLayoutConstraint(item: self.webView as Any, attribute: NSLayoutConstraint.Attribute.leading, relatedBy: NSLayoutConstraint.Relation.equal, toItem: self.webViewContainer, attribute: NSLayoutConstraint.Attribute.leading, multiplier: 1, constant: 0)
  86. self.webViewContainer.addConstraints([top, bottom, trailing, leading])
  87. webView.navigationDelegate = self
  88. webView.uiDelegate = self
  89. webView.allowsBackForwardNavigationGestures = true
  90. loadItemDetail()
  91. }
  92. @objc func goBack() {
  93. if self.fromCreateDocVC {//创建文档页面跳过来的 返回的时候就多跳一级
  94. self.performSegue(withIdentifier: "back2DocumentListSegue", sender: nil)
  95. } else {
  96. self.navigationController?.popViewController(animated: false)
  97. }
  98. }
  99. private func qlInit(){
  100. // 文档查看器
  101. self.qlController.dataSource = qlController
  102. self.qlController.delegate = qlController
  103. }
  104. private func loadItemDetail() {
  105. DDLogDebug("url:\(itemUrl)")
  106. webView.load(Alamofire.request(itemUrl).request!)
  107. }
  108. @objc private func qlCloseWindow(){
  109. self.dismiss(animated: true, completion: {
  110. })
  111. }
  112. private func setupBottomToolbar() {
  113. var items: [UIBarButtonItem] = []
  114. if self.myControl != nil {
  115. let spaceItem = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: self, action: nil)
  116. if let allowDelete = self.myControl!["allowDeleteDocument"] as? Bool {
  117. if allowDelete { //删除文档
  118. DDLogDebug("删除文档。。。。。。。。。。。。。。。。。。。。。。安装按钮")
  119. let deleteBtn = UIButton(frame: CGRect(x: 0, y: 0, width: 30, height: 30))
  120. deleteBtn.setTitle("删除", for: .normal)
  121. deleteBtn.setTitleColor(base_color, for: .normal)
  122. deleteBtn.addTapGesture { (tap) in
  123. self.itemBtnDocDeleteAction()
  124. }
  125. let deleteItem = UIBarButtonItem(customView: deleteBtn)
  126. items.append(spaceItem)
  127. items.append(deleteItem)
  128. items.append(spaceItem)
  129. }
  130. }
  131. if let allowPublishDocument = self.myControl!["allowPublishDocument"] as? Bool {
  132. if allowPublishDocument { //发布文档
  133. DDLogDebug("发布文档。。。。。。。。。。。。。。。。。。。。。。安装按钮")
  134. let publishBtn = UIButton(frame: CGRect(x: 0, y: 0, width: 30, height: 30))
  135. publishBtn.setTitle("发布", for: .normal)
  136. publishBtn.setTitleColor(base_color, for: .normal)
  137. publishBtn.addTapGesture { (tap) in
  138. self.itemBtnDocPublishAction()
  139. }
  140. let publishItem = UIBarButtonItem(customView: publishBtn)
  141. items.append(spaceItem)
  142. items.append(publishItem)
  143. items.append(spaceItem)
  144. }
  145. }
  146. self.layoutBottomBar(items: items)
  147. }
  148. }
  149. private func layoutBottomBar(items: [UIBarButtonItem]) {
  150. if items.count > 0 {
  151. self.toolbarView.items = items
  152. self.view.addSubview(self.toolbarView)
  153. self.toolbarView.translatesAutoresizingMaskIntoConstraints = false
  154. let heightC = NSLayoutConstraint(item: self.toolbarView as Any, attribute: NSLayoutConstraint.Attribute.height, relatedBy: NSLayoutConstraint.Relation.equal, toItem: nil, attribute: NSLayoutConstraint.Attribute.notAnAttribute, multiplier: 0.0, constant: 44)
  155. self.toolbarView.addConstraint(heightC)
  156. let bottom = NSLayoutConstraint(item: self.toolbarView as Any, attribute: NSLayoutConstraint.Attribute.bottom, relatedBy: NSLayoutConstraint.Relation.equal, toItem: self.view, attribute: NSLayoutConstraint.Attribute.bottom, multiplier: 1, constant: 0)
  157. let trailing = NSLayoutConstraint(item: self.toolbarView as Any, attribute: NSLayoutConstraint.Attribute.trailing, relatedBy: NSLayoutConstraint.Relation.equal, toItem: self.view, attribute: NSLayoutConstraint.Attribute.trailing, multiplier: 1, constant: 0)
  158. let leading = NSLayoutConstraint(item: self.toolbarView as Any, attribute: NSLayoutConstraint.Attribute.leading, relatedBy: NSLayoutConstraint.Relation.equal, toItem: self.view, attribute: NSLayoutConstraint.Attribute.leading, multiplier: 1, constant: 0)
  159. self.view.addConstraints([bottom, leading, trailing])
  160. self.view.constraints.forEach { (constraint) in
  161. if constraint.identifier == "webViewContainerBottom" {
  162. self.view.removeConstraint(constraint)
  163. }
  164. }
  165. let webcTop = NSLayoutConstraint(item: self.webViewContainer as Any, attribute: NSLayoutConstraint.Attribute.bottom, relatedBy: NSLayoutConstraint.Relation.equal, toItem: self.toolbarView, attribute: NSLayoutConstraint.Attribute.top, multiplier: 1, constant: 0)
  166. self.view.addConstraint(webcTop)
  167. self.view.layoutIfNeeded()
  168. }
  169. }
  170. //删除文档
  171. private func itemBtnDocDeleteAction() {
  172. self.showDefaultConfirm(title: "提示", message: "你确定要删除当前文档?") { (action) in
  173. let callJS = "layout.appForm.deleteDocumentForMobile()"
  174. self.webView.evaluateJavaScript(callJS, completionHandler: { (result, err) in
  175. //
  176. })
  177. }
  178. }
  179. //发布文档 layout.appForm.publishDocument()
  180. private func itemBtnDocPublishAction() {
  181. let callJS = "layout.appForm.publishDocument()"
  182. self.webView.evaluateJavaScript(callJS, completionHandler: { (result, err) in
  183. //
  184. })
  185. }
  186. }
  187. extension CMSItemDetailViewController:WKNavigationDelegate,WKUIDelegate {
  188. func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {
  189. DDLogDebug("didFailProvisionalNavigation \(String(describing: navigation)) error = \(error)")
  190. }
  191. func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
  192. DDLogDebug("didStartProvisionalNavigation \(String(describing: navigation))")
  193. }
  194. func webView(_ webView: WKWebView, didCommit navigation: WKNavigation!) {
  195. DDLogDebug("didCommit")
  196. }
  197. func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
  198. DDLogDebug("didFinish")
  199. //self.setupData()
  200. }
  201. func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
  202. DDLogDebug("didFail")
  203. DDLogError(error.localizedDescription)
  204. }
  205. }
  206. //MARK: js脚本
  207. extension CMSItemDetailViewController: O2WKScriptMessageHandlerImplement {
  208. func userController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
  209. let name = message.name
  210. switch name {
  211. case "cmsFormLoaded":
  212. DDLogDebug("cmsFormLoaded start。。。。")
  213. if let newControls = (message.body as? NSString) {
  214. let str = newControls as String
  215. DDLogDebug("cmsFormLoaded , controls :\(str)")
  216. let json = JSON.init(parseJSON: str)
  217. self.myControl = json.dictionaryObject! as [String: AnyObject]
  218. self.setupBottomToolbar()
  219. }
  220. break
  221. case "uploadAttachment":
  222. ZonePermissions.requestImagePickerAuthorization(callback: { (zoneStatus) in
  223. if zoneStatus == ZoneAuthorizationStatus.zAuthorizationStatusAuthorized {
  224. let site = (message.body as! NSDictionary)["site"]
  225. self.uploadAttachment(site as! String)
  226. }else {
  227. self.gotoApplicationSettings(alertMessage: "需要照片允许访问权限,是否跳转到手机设置页面开启相机权限?")
  228. }
  229. })
  230. break
  231. case "downloadAttachment":
  232. let attachmentId = (message.body as! NSDictionary)["id"]
  233. self.downloadAttachment(attachmentId as! String)
  234. break
  235. case "replaceAttachment":
  236. let attachmentId = (message.body as! NSDictionary)["id"] as! String
  237. let site = (message.body as! NSDictionary)["site"] as? String
  238. self.replaceAttachment(attachmentId, site ?? "")
  239. break
  240. case "openDocument":
  241. let url = (message.body as! NSString)
  242. self.downloadDocumentAndPreview(String(url))
  243. break
  244. case "closeDocumentWindow":
  245. self.goBack()
  246. break
  247. default:
  248. DDLogError("未知方法名:\(name)!")
  249. break
  250. }
  251. }
  252. //上传附件
  253. private func uploadAttachment(_ site:String){
  254. //选择附件上传
  255. var id = ""
  256. if self.documentId != nil {
  257. id = self.documentId!
  258. }else {
  259. id = self.itemData!.id!
  260. }
  261. let updloadURL = AppDelegate.o2Collect.generateURLWithAppContextKey(CMSContext.cmsContextKey, query: CMSContext.cmsAttachmentUpload, parameter: ["##docId##":id as AnyObject])
  262. self.uploadAttachment(site, uploadURL: updloadURL!)
  263. }
  264. private func uploadAttachment(_ site:String,uploadURL url:String){
  265. let vc = FileBSImagePickerViewController()
  266. bs_presentImagePickerController(vc, animated: true,
  267. select: { (asset: PHAsset) -> Void in
  268. // User selected an asset.
  269. // Do something with it, start upload perhaps?
  270. }, deselect: { (asset: PHAsset) -> Void in
  271. // User deselected an assets.
  272. // Do something, cancel upload?
  273. }, cancel: { (assets: [PHAsset]) -> Void in
  274. // User cancelled. And this where the assets currently selected.
  275. }, finish: { (assets: [PHAsset]) -> Void in
  276. for asset in assets {
  277. switch asset.mediaType {
  278. case .audio:
  279. DDLogDebug("Audio")
  280. case .image:
  281. let options = PHImageRequestOptions()
  282. options.isSynchronous = true
  283. options.deliveryMode = .fastFormat
  284. options.resizeMode = .none
  285. PHImageManager.default().requestImageData(for: asset, options: options, resultHandler: { (imageData, result, imageOrientation, dict) in
  286. //DDLogDebug("result = \(result) imageOrientation = \(imageOrientation) \(dict)")
  287. let fileURL = dict?["PHImageFileURLKey"] as! URL
  288. DispatchQueue.main.async {
  289. self.showMessage(title: "上传中...")
  290. }
  291. DispatchQueue.global(qos: .userInitiated).async {
  292. Alamofire.upload(multipartFormData: { (mData) in
  293. //mData.append(fileURL, withName: "file")
  294. mData.append(imageData!, withName: "file", fileName: fileURL.lastPathComponent, mimeType: "application/octet-stream")
  295. let siteData = site.data(using: String.Encoding.utf8, allowLossyConversion: false)
  296. mData.append(siteData!, withName: "site")
  297. }, to: url, encodingCompletion: { (encodingResult) in
  298. switch encodingResult {
  299. case .success(let upload, _, _):
  300. debugPrint(upload)
  301. upload.responseJSON {
  302. respJSON in
  303. switch respJSON.result {
  304. case .success(let val):
  305. let attachId = JSON(val)["data"]["id"].string!
  306. DispatchQueue.main.async {
  307. //ProgressHUD.showSuccess("上传成功")
  308. let callJS = "layout.appForm.uploadedAttachment(\"\(site)\", \"\(attachId)\")"
  309. self.webView.evaluateJavaScript(callJS, completionHandler: { (result, err) in
  310. self.showSuccess(title: "上传成功")
  311. })
  312. }
  313. case .failure(let err):
  314. DispatchQueue.main.async {
  315. DDLogError(err.localizedDescription)
  316. self.showError(title: "上传失败")
  317. }
  318. break
  319. }
  320. }
  321. case .failure(let errType):
  322. DispatchQueue.main.async {
  323. DDLogError(errType.localizedDescription)
  324. self.showError(title: "上传失败")
  325. }
  326. }
  327. })
  328. }
  329. })
  330. case .video:
  331. DDLogDebug("video")
  332. case .unknown:
  333. DDLogDebug("Unknown")
  334. @unknown default:
  335. DDLogDebug("Unknown")
  336. }
  337. }
  338. }, completion: nil)
  339. }
  340. //下载预览附件
  341. private func downloadAttachment(_ attachmentId:String){
  342. //文档id
  343. var id: String?
  344. if self.documentId != nil {
  345. id = self.documentId
  346. }else {
  347. id = self.itemData?.id
  348. }
  349. if id == nil {
  350. self.showError(title: "下载文件出错")
  351. return
  352. }
  353. //
  354. let attachInfoURL = AppDelegate.o2Collect.generateURLWithAppContextKey(CMSContext.cmsContextKey, query: CMSContext.cmsAttachmentGET, parameter: ["##attachId##":attachmentId as AnyObject, "##documentId##": id as AnyObject])
  355. //附件下载链接
  356. let downURL = AppDelegate.o2Collect.generateURLWithAppContextKey(CMSContext.cmsContextKey, query: CMSContext.cmsAttachmentDownloadNewQuery, parameter: ["##attachId##":attachmentId as AnyObject])
  357. self.showMessage(title: "下载中...")
  358. // 先获取附件对象
  359. Alamofire.request(attachInfoURL!).responseJSON { (response) in
  360. switch response.result {
  361. case .success(let val):
  362. let info = Mapper<CMSAttachmentInfoResponse>().map(JSONString: JSON(val).description)
  363. if let fileName = info?.data?.name {
  364. //执行下载
  365. let destination: DownloadRequest.DownloadFileDestination = { _, _ in
  366. let documentsURL = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask)[0]
  367. let fileURL = documentsURL.appendingPathComponent(fileName)
  368. return (fileURL, [.removePreviousFile, .createIntermediateDirectories])
  369. }
  370. //然后下载附件
  371. Alamofire.download(downURL!, to: destination).response(completionHandler: { (response) in
  372. if response.error == nil , let fileurl = response.destinationURL?.path {
  373. //打开文件
  374. self.dismissProgressHUD()
  375. self.previewAttachment(fileurl)
  376. }else{
  377. DispatchQueue.main.async {
  378. self.showError(title: "下载文件出错")
  379. }
  380. }
  381. })
  382. }else {
  383. DispatchQueue.main.async {
  384. self.showError(title: "下载文件出错")
  385. }
  386. }
  387. break
  388. case .failure(let err):
  389. DDLogError(err.localizedDescription)
  390. DispatchQueue.main.async {
  391. self.showError(title: "下载文件出错")
  392. }
  393. break
  394. }
  395. }
  396. }
  397. //替换附件
  398. private func replaceAttachment(_ attachmentId:String, _ site:String){
  399. var id = ""
  400. if self.documentId != nil {
  401. id = self.documentId!
  402. }else {
  403. id = self.itemData!.id!
  404. }
  405. let replaceURL = AppDelegate.o2Collect.generateURLWithAppContextKey(CMSContext.cmsContextKey, query: CMSContext.cmsAttachmentReplace, parameter: ["##attachId##":attachmentId as AnyObject,"##docId##": id as AnyObject])!
  406. self.replaceAttachment(site, attachmentId, replaceURL: replaceURL)
  407. }
  408. /**
  409. * 下载公文 并阅览
  410. **/
  411. private func downloadDocumentAndPreview(_ url: String) {
  412. DDLogDebug("文档下载地址:\(url)")
  413. self.showMessage(title: "下载中...")
  414. // 文件地址
  415. let localFileDestination: DownloadRequest.DownloadFileDestination = { _, response in
  416. let documentsURL = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask)[0]
  417. let fileURL = documentsURL.appendingPathComponent(response.suggestedFilename!)
  418. // 有重名文件就删除重建
  419. return (fileURL, [.removePreviousFile, .createIntermediateDirectories])
  420. }
  421. Alamofire.download(url, to: localFileDestination).response(completionHandler: { (response) in
  422. if response.error == nil , let fileurl = response.destinationURL?.path {
  423. DDLogDebug("文件地址:\(fileurl)")
  424. //打开文件
  425. self.dismissProgressHUD()
  426. self.previewAttachment(fileurl)
  427. }else{
  428. let msg = response.error?.localizedDescription ?? ""
  429. DDLogError("下载文件出错,\(msg)")
  430. DispatchQueue.main.async {
  431. self.showError(title: "预览文件出错")
  432. }
  433. }
  434. })
  435. }
  436. private func previewAttachment(_ url:String){
  437. let currentURL = NSURL(fileURLWithPath: url)
  438. if QLPreviewController.canPreview(currentURL) {
  439. self.qlController.currentFileURLS.removeAll(keepingCapacity: true)
  440. self.qlController.currentFileURLS.append(currentURL)
  441. self.qlController.reloadData()
  442. if #available(iOS 10, *) {
  443. let navVC = ZLNormalNavViewController(rootViewController: qlController)
  444. qlController.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .plain, target: qlController, action: #selector(qlController.qlCloseWindow))
  445. self.presentVC(navVC)
  446. }else{
  447. self.pushVC(qlController)
  448. }
  449. }else{
  450. self.showError(title: "此文件无法预览,请在PC端查看")
  451. }
  452. }
  453. private func replaceAttachment(_ site:String,_ attachmentId:String,replaceURL url:String){
  454. let vc = FileBSImagePickerViewController()
  455. bs_presentImagePickerController(vc, animated: true,
  456. select: { (asset: PHAsset) -> Void in
  457. // User selected an asset.
  458. // Do something with it, start upload perhaps?
  459. }, deselect: { (asset: PHAsset) -> Void in
  460. // User deselected an assets.
  461. // Do something, cancel upload?
  462. }, cancel: { (assets: [PHAsset]) -> Void in
  463. // User cancelled. And this where the assets currently selected.
  464. }, finish: { (assets: [PHAsset]) -> Void in
  465. for asset in assets {
  466. switch asset.mediaType {
  467. case .audio:
  468. DDLogDebug("Audio")
  469. case .image:
  470. let options = PHImageRequestOptions()
  471. options.isSynchronous = true
  472. options.deliveryMode = .fastFormat
  473. options.resizeMode = .none
  474. PHImageManager.default().requestImageData(for: asset, options: options, resultHandler: { (imageData, result, imageOrientation, dict) in
  475. //DDLogDebug("result = \(result) imageOrientation = \(imageOrientation) \(dict)")
  476. let fileURL = dict?["PHImageFileURLKey"] as! URL
  477. DispatchQueue.main.async {
  478. self.showMessage(title: "上传中...")
  479. }
  480. DispatchQueue.global(qos: .userInitiated).async {
  481. Alamofire.upload(multipartFormData: { (mData) in
  482. //mData.append(fileURL, withName: "file")
  483. mData.append(imageData!, withName: "file", fileName: fileURL.lastPathComponent, mimeType: "application/octet-stream")
  484. let siteData = site.data(using: String.Encoding.utf8, allowLossyConversion: false)
  485. mData.append(siteData!, withName: "site")
  486. }, usingThreshold: SessionManager.multipartFormDataEncodingMemoryThreshold, to: url, method: .put, headers: nil, encodingCompletion: { (encodingResult) in
  487. switch encodingResult {
  488. case .success(let upload, _, _):
  489. debugPrint(upload)
  490. upload.responseJSON {
  491. respJSON in
  492. switch respJSON.result {
  493. case .success( _):
  494. DispatchQueue.main.async {
  495. let callJS = "layout.appForm.replacedAttachment(\"\(site)\", \"\(attachmentId)\")"
  496. self.webView.evaluateJavaScript(callJS, completionHandler: { (result, err) in
  497. self.showSuccess(title: "替换成功")
  498. })
  499. }
  500. case .failure(let err):
  501. DispatchQueue.main.async {
  502. DDLogError(err.localizedDescription)
  503. self.showError(title: "替换失败")
  504. }
  505. break
  506. }
  507. }
  508. case .failure(let errType):
  509. DispatchQueue.main.async {
  510. DDLogError(errType.localizedDescription)
  511. self.showError(title: "替换失败")
  512. }
  513. }
  514. })
  515. }
  516. })
  517. case .video:
  518. DDLogDebug("video")
  519. case .unknown:
  520. DDLogDebug("Unknown")
  521. @unknown default:
  522. DDLogDebug("Unknown")
  523. }
  524. }
  525. }, completion: nil)
  526. }
  527. }