IMChatViewController.swift 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697
  1. //
  2. // IMChatViewController.swift
  3. // O2Platform
  4. //
  5. // Created by FancyLou on 2020/6/8.
  6. // Copyright © 2020 zoneland. All rights reserved.
  7. //
  8. import UIKit
  9. import CocoaLumberjack
  10. import O2OA_Auth_SDK
  11. import BSImagePicker
  12. import Photos
  13. import Alamofire
  14. import AlamofireImage
  15. import SwiftyJSON
  16. import QuickLook
  17. class IMChatViewController: UIViewController {
  18. // MARK: - IBOutlet
  19. //消息列表
  20. @IBOutlet weak var tableView: UITableView!
  21. //消息输入框
  22. @IBOutlet weak var messageInputView: UITextField!
  23. //底部工具栏的高度约束
  24. @IBOutlet weak var bottomBarHeightConstraint: NSLayoutConstraint!
  25. //底部工具栏
  26. @IBOutlet weak var bottomBar: UIView!
  27. private let emojiBarHeight = 196
  28. //表情窗口
  29. private lazy var emojiBar: IMChatEmojiBarView = {
  30. let view = Bundle.main.loadNibNamed("IMChatEmojiBarView", owner: self, options: nil)?.first as! IMChatEmojiBarView
  31. view.frame = CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: emojiBarHeight.toCGFloat)
  32. return view
  33. }()
  34. //语音录制按钮
  35. private lazy var audioBtnView: IMChatAudioView = {
  36. let view = Bundle.main.loadNibNamed("IMChatAudioView", owner: self, options: nil)?.first as! IMChatAudioView
  37. view.frame = CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: emojiBarHeight.toCGFloat)
  38. view.delegate = self
  39. return view
  40. }()
  41. //预览文件
  42. private lazy var previewVC: CloudFilePreviewController = {
  43. return CloudFilePreviewController()
  44. }()
  45. private lazy var viewModel: IMViewModel = {
  46. return IMViewModel()
  47. }()
  48. // MARK: - properties
  49. var conversation: IMConversationInfo? = nil
  50. //private
  51. private var chatMessageList: [IMMessageInfo] = []
  52. private var page = 1
  53. private var isShowEmoji = false
  54. private var isShowAudioView = false
  55. private var bottomBarHeight = 64 //底部输入框 表情按钮 的高度
  56. private let bottomToolbarHeight = 46 //底部工具栏 麦克风 相册 相机等按钮的位置
  57. // MARK: - functions
  58. override func viewDidLoad() {
  59. super.viewDidLoad()
  60. self.tableView.delegate = self
  61. self.tableView.dataSource = self
  62. self.tableView.register(UINib(nibName: "IMChatMessageViewCell", bundle: nil), forCellReuseIdentifier: "IMChatMessageViewCell")
  63. self.tableView.register(UINib(nibName: "IMChatMessageSendViewCell", bundle: nil), forCellReuseIdentifier: "IMChatMessageSendViewCell")
  64. self.tableView.separatorStyle = .none
  65. // self.tableView.rowHeight = UITableView.automaticDimension
  66. // self.tableView.estimatedRowHeight = 144
  67. self.tableView.backgroundColor = UIColor(hex: "#f3f3f3")
  68. self.messageInputView.delegate = self
  69. //底部安全距离 老机型没有
  70. self.bottomBarHeight = Int(iPhoneX ? 64 + IPHONEX_BOTTOM_SAFE_HEIGHT: 64) + self.bottomToolbarHeight
  71. self.bottomBarHeightConstraint.constant = self.bottomBarHeight.toCGFloat
  72. self.bottomBar.topBorder(width: 1, borderColor: base_gray_color.alpha(0.5))
  73. self.messageInputView.backgroundColor = base_gray_color
  74. //标题
  75. if self.conversation?.type == o2_im_conversation_type_single {
  76. if let c = self.conversation {
  77. var person = ""
  78. c.personList?.forEach({ (p) in
  79. if p != O2AuthSDK.shared.myInfo()?.distinguishedName {
  80. person = p
  81. }
  82. })
  83. if !person.isEmpty {
  84. self.title = person.split("@").first ?? ""
  85. }
  86. }
  87. } else {
  88. self.title = self.conversation?.title
  89. }
  90. //群会话 添加修改标题的按钮
  91. if self.conversation?.type == o2_im_conversation_type_group &&
  92. O2AuthSDK.shared.myInfo()?.distinguishedName == self.conversation?.adminPerson {
  93. navigationItem.rightBarButtonItem = UIBarButtonItem(title: "修改", style: .plain, target: self, action: #selector(clickUpdate))
  94. }
  95. //获取聊天数据
  96. self.loadMsgList(page: page)
  97. //阅读
  98. self.viewModel.readConversation(conversationId: self.conversation?.id)
  99. }
  100. override func viewWillAppear(_ animated: Bool) {
  101. NotificationCenter.default.addObserver(self, selector: #selector(receiveMessageFromWs(notice:)), name: OONotification.websocket.notificationName, object: nil)
  102. }
  103. override func viewWillDisappear(_ animated: Bool) {
  104. NotificationCenter.default.removeObserver(self)
  105. }
  106. @objc private func receiveMessageFromWs(notice: Notification) {
  107. DDLogDebug("接收到websocket im 消息")
  108. if let message = notice.object as? IMMessageInfo {
  109. if message.conversationId == self.conversation?.id {
  110. self.chatMessageList.append(message)
  111. self.scrollMessageToBottom()
  112. self.viewModel.readConversation(conversationId: self.conversation?.id)
  113. }
  114. }
  115. }
  116. @objc private func clickUpdate() {
  117. self.showSheetAction(title: "", message: "选择要修改的项", actions: [
  118. UIAlertAction(title: "修改群名", style: .default, handler: { (action) in
  119. self.updateTitle()
  120. }),
  121. UIAlertAction(title: "修改成员", style: .default, handler: { (action) in
  122. self.updatePeople()
  123. })
  124. ])
  125. }
  126. private func updateTitle() {
  127. self.showPromptAlert(title: "", message: "修改群名", inputText: "") { (action, result) in
  128. if result.isEmpty {
  129. self.showError(title: "请输入群名")
  130. }else {
  131. self.showLoading()
  132. self.viewModel.updateConversationTitle(id: (self.conversation?.id!)!, title: result)
  133. .then { (c) in
  134. self.title = result
  135. self.conversation?.title = result
  136. self.showSuccess(title: "修改成功")
  137. }.catch { (err) in
  138. DDLogError(err.localizedDescription)
  139. self.showError(title: "修改失败")
  140. }
  141. }
  142. }
  143. }
  144. private func updatePeople() {
  145. //选择人员 反选已经存在的成员
  146. if let users = self.conversation?.personList {
  147. self.showContactPicker(modes: [.person], callback: { (result) in
  148. if let people = result.users {
  149. if people.count >= 3 {
  150. var peopleDNs: [String] = []
  151. var containMe = false
  152. people.forEach { (item) in
  153. peopleDNs.append(item.distinguishedName!)
  154. if O2AuthSDK.shared.myInfo()?.distinguishedName == item.distinguishedName {
  155. containMe = true
  156. }
  157. }
  158. if !containMe {
  159. peopleDNs.append((O2AuthSDK.shared.myInfo()?.distinguishedName)!)
  160. }
  161. self.showLoading()
  162. self.viewModel.updateConversationPeople(id: (self.conversation?.id!)!, users: peopleDNs)
  163. .then { (c) in
  164. self.conversation?.personList = peopleDNs
  165. self.showSuccess(title: "修改成功")
  166. }.catch { (err) in
  167. DDLogError(err.localizedDescription)
  168. self.showError(title: "修改失败")
  169. }
  170. }else {
  171. self.showError(title: "选择人数不足3人")
  172. }
  173. }else {
  174. self.showError(title: "请选择人员")
  175. }
  176. }, initUserPickedArray: users)
  177. }else {
  178. self.showError(title: "成员列表数据错误!")
  179. }
  180. }
  181. //获取消息
  182. private func loadMsgList(page: Int) {
  183. if let c = self.conversation, let id = c.id {
  184. self.viewModel.myMsgPageList(page: page, conversationId: id).then { (list) in
  185. self.chatMessageList = list
  186. self.scrollMessageToBottom()
  187. }
  188. } else {
  189. self.showError(title: "参数错误!!!")
  190. }
  191. }
  192. //刷新tableview 滚动到底部
  193. private func scrollMessageToBottom() {
  194. DispatchQueue.main.async {
  195. self.tableView.reloadData()
  196. if self.chatMessageList.count > 0 {
  197. self.tableView.scrollToRow(at: IndexPath(row: self.chatMessageList.count - 1, section: 0), at: .bottom, animated: true)
  198. }
  199. }
  200. }
  201. //发送文本消息
  202. private func sendTextMessage() {
  203. guard let msg = self.messageInputView.text else {
  204. return
  205. }
  206. self.messageInputView.text = ""
  207. let body = IMMessageBodyInfo()
  208. body.type = o2_im_msg_type_text
  209. body.body = msg
  210. sendMessage(body: body)
  211. }
  212. //发送表情消息
  213. private func sendEmojiMessage(emoji: String) {
  214. let body = IMMessageBodyInfo()
  215. body.type = o2_im_msg_type_emoji
  216. body.body = emoji
  217. sendMessage(body: body)
  218. }
  219. //发送地图消息消息
  220. private func sendLocationMessage(loc: O2LocationData) {
  221. let body = IMMessageBodyInfo()
  222. body.type = o2_im_msg_type_location
  223. body.body = o2_im_msg_body_location
  224. body.address = loc.address
  225. body.addressDetail = loc.addressDetail
  226. body.longitude = loc.longitude
  227. body.latitude = loc.latitude
  228. sendMessage(body: body)
  229. }
  230. //发送消息到服务器
  231. private func sendMessage(body: IMMessageBodyInfo) {
  232. let message = IMMessageInfo()
  233. message.body = body.toJSONString()
  234. message.id = UUID().uuidString
  235. message.conversationId = self.conversation?.id
  236. message.createPerson = O2AuthSDK.shared.myInfo()?.distinguishedName
  237. message.createTime = Date().formatterDate(formatter: "yyyy-MM-dd HH:mm:ss")
  238. //添加到界面
  239. self.chatMessageList.append(message)
  240. self.scrollMessageToBottom()
  241. //发送消息到服务器
  242. self.viewModel.sendMsg(msg: message)
  243. .then { (result) in
  244. DDLogDebug("发送消息成功 \(result)")
  245. self.viewModel.readConversation(conversationId: self.conversation?.id)
  246. }.catch { (error) in
  247. DDLogError(error.localizedDescription)
  248. self.showError(title: "发送消息失败!")
  249. }
  250. }
  251. //选择照片
  252. private func chooseImage() {
  253. let vc = FileBSImagePickerViewController().bsImagePicker()
  254. vc.settings.fetch.assets.supportedMediaTypes = [.image]
  255. presentImagePicker(vc, select: { (asset) in
  256. //选中一个
  257. }, deselect: { (asset) in
  258. //取消选中一个
  259. }, cancel: { (assets) in
  260. //取消
  261. }, finish: { (assets) in
  262. //结果
  263. if assets.count > 0 {
  264. switch assets[0].mediaType {
  265. case .image:
  266. let options = PHImageRequestOptions()
  267. options.isSynchronous = true
  268. options.deliveryMode = .fastFormat
  269. options.resizeMode = .none
  270. PHImageManager.default().requestImageData(for: assets[0], options: options) { (imageData, result, imageOrientation, dict) in
  271. guard let data = imageData else {
  272. return
  273. }
  274. var newData = data
  275. //处理图片旋转的问题
  276. if imageOrientation != UIImage.Orientation.up {
  277. let newImage = UIImage(data: data)?.fixOrientation()
  278. if newImage != nil {
  279. newData = newImage!.pngData()!
  280. }
  281. }
  282. var fileName = ""
  283. if dict?["PHImageFileURLKey"] != nil {
  284. let fileURL = dict?["PHImageFileURLKey"] as! URL
  285. fileName = fileURL.lastPathComponent
  286. } else {
  287. fileName = "\(UUID().uuidString).png"
  288. }
  289. let localFilePath = self.storageLocalImage(imageData: newData, fileName: fileName)
  290. let msgId = self.prepareForSendImageMsg(filePath: localFilePath)
  291. self.uploadFileAndSendMsg(messageId: msgId, data: newData, fileName: fileName, type: o2_im_msg_type_image)
  292. }
  293. break
  294. default:
  295. //
  296. DDLogError("不支持的类型")
  297. self.showError(title: "不支持的类型!")
  298. break
  299. }
  300. }
  301. }, completion: nil)
  302. }
  303. //临时存储本地
  304. private func storageLocalImage(imageData: Data, fileName: String) -> String {
  305. let fileTempPath = FileUtil.share.cacheDir().appendingPathComponent(fileName)
  306. do {
  307. try imageData.write(to: fileTempPath)
  308. return fileTempPath.path
  309. } catch {
  310. print(error.localizedDescription)
  311. return fileTempPath.path
  312. }
  313. }
  314. //发送消息前 先载入界面
  315. private func prepareForSendImageMsg(filePath: String) -> String {
  316. let body = IMMessageBodyInfo()
  317. body.type = o2_im_msg_type_image
  318. body.body = o2_im_msg_body_image
  319. body.fileTempPath = filePath
  320. let message = IMMessageInfo()
  321. let msgId = UUID().uuidString
  322. message.body = body.toJSONString()
  323. message.id = msgId
  324. message.conversationId = self.conversation?.id
  325. message.createPerson = O2AuthSDK.shared.myInfo()?.distinguishedName
  326. message.createTime = Date().formatterDate(formatter: "yyyy-MM-dd HH:mm:ss")
  327. //添加到界面
  328. self.chatMessageList.append(message)
  329. self.scrollMessageToBottom()
  330. return msgId
  331. }
  332. //发送消息前 先载入界面
  333. private func prepareForSendFileMsg(tempMessage: IMMessageBodyInfo) -> String {
  334. let message = IMMessageInfo()
  335. let msgId = UUID().uuidString
  336. message.body = tempMessage.toJSONString()
  337. message.id = msgId
  338. message.conversationId = self.conversation?.id
  339. message.createPerson = O2AuthSDK.shared.myInfo()?.distinguishedName
  340. message.createTime = Date().formatterDate(formatter: "yyyy-MM-dd HH:mm:ss")
  341. //添加到界面
  342. self.chatMessageList.append(message)
  343. self.scrollMessageToBottom()
  344. return msgId
  345. }
  346. //上传图片 音频 等文件到服务器并发送消息
  347. private func uploadFileAndSendMsg(messageId: String, data: Data, fileName: String, type: String) {
  348. guard let cId = self.conversation?.id else {
  349. return
  350. }
  351. self.viewModel.uploadFile(conversationId: cId, type: type, fileName: fileName, file: data).then { back in
  352. DDLogDebug("上传文件成功")
  353. guard let message = self.chatMessageList.first (where: { (info) -> Bool in
  354. return info.id == messageId
  355. }) else {
  356. DDLogDebug("没有找到对应的消息")
  357. return
  358. }
  359. let body = IMMessageBodyInfo.deserialize(from: message.body)
  360. body?.fileId = back.id
  361. body?.fileExtension = back.fileExtension
  362. body?.fileTempPath = nil
  363. message.body = body?.toJSONString()
  364. //发送消息到服务器
  365. self.viewModel.sendMsg(msg: message)
  366. .then { (result) in
  367. DDLogDebug("消息 发送成功 \(result)")
  368. self.viewModel.readConversation(conversationId: self.conversation?.id)
  369. }.catch { (error) in
  370. DDLogError(error.localizedDescription)
  371. self.showError(title: "发送消息失败!")
  372. }
  373. }.catch { err in
  374. self.showError(title: "上传错误,\(err.localizedDescription)")
  375. }
  376. }
  377. // MARK: - IBAction
  378. //点击表情按钮
  379. @IBAction func clickEmojiBtn(_ sender: UIButton) {
  380. self.isShowEmoji.toggle()
  381. self.view.endEditing(true)
  382. if self.isShowEmoji {
  383. //audio view 先关闭
  384. self.isShowAudioView = false
  385. self.audioBtnView.removeFromSuperview()
  386. //开始添加emojiBar
  387. self.bottomBarHeightConstraint.constant = self.bottomBarHeight.toCGFloat + self.emojiBarHeight.toCGFloat
  388. self.emojiBar.delegate = self
  389. self.emojiBar.translatesAutoresizingMaskIntoConstraints = false
  390. self.bottomBar.addSubview(self.emojiBar)
  391. let top = NSLayoutConstraint(item: self.emojiBar, attribute: .top, relatedBy: .equal, toItem: self.emojiBar.superview!, attribute: .top, multiplier: 1, constant: CGFloat(self.bottomBarHeight))
  392. let width = NSLayoutConstraint(item: self.emojiBar, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: SCREEN_WIDTH)
  393. let height = NSLayoutConstraint(item: self.emojiBar, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: self.emojiBarHeight.toCGFloat)
  394. NSLayoutConstraint.activate([top, width, height])
  395. } else {
  396. self.bottomBarHeightConstraint.constant = self.bottomBarHeight.toCGFloat
  397. self.emojiBar.removeFromSuperview()
  398. }
  399. self.view.layoutIfNeeded()
  400. }
  401. @IBAction func micBtnClick(_ sender: UIButton) {
  402. DDLogDebug("点击了麦克风按钮")
  403. self.isShowAudioView.toggle()
  404. self.view.endEditing(true)
  405. if self.isShowAudioView {
  406. //emoji view 先关闭
  407. self.isShowEmoji = false
  408. self.emojiBar.removeFromSuperview()
  409. //开始添加emojiBar
  410. self.bottomBarHeightConstraint.constant = self.bottomBarHeight.toCGFloat + self.emojiBarHeight.toCGFloat
  411. self.audioBtnView.translatesAutoresizingMaskIntoConstraints = false
  412. self.bottomBar.addSubview(self.audioBtnView)
  413. let top = NSLayoutConstraint(item: self.audioBtnView, attribute: .top, relatedBy: .equal, toItem: self.audioBtnView.superview!, attribute: .top, multiplier: 1, constant: CGFloat(self.bottomBarHeight))
  414. let width = NSLayoutConstraint(item: self.audioBtnView, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: SCREEN_WIDTH)
  415. let height = NSLayoutConstraint(item: self.audioBtnView, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: self.emojiBarHeight.toCGFloat)
  416. NSLayoutConstraint.activate([top, width, height])
  417. } else {
  418. self.bottomBarHeightConstraint.constant = self.bottomBarHeight.toCGFloat
  419. self.audioBtnView.removeFromSuperview()
  420. }
  421. self.view.layoutIfNeeded()
  422. }
  423. @IBAction func imgBtnClick(_ sender: UIButton) {
  424. DDLogDebug("点击了图片按钮")
  425. self.chooseImage()
  426. }
  427. @IBAction func cameraBtnClick(_ sender: UIButton) {
  428. DDLogDebug("点击了相机按钮")
  429. self.takePhoto(delegate: self)
  430. }
  431. @IBAction func locationBtnClick(_ sender: UIButton) {
  432. DDLogDebug("点击了位置按钮")
  433. let vc = IMLocationChooseController.openChooseLocation { (data) in
  434. self.sendLocationMessage(loc: data)
  435. }
  436. self.navigationController?.pushViewController(vc, animated: false)
  437. }
  438. }
  439. // MARK: - 录音delegate
  440. extension IMChatViewController: IMChatAudioViewDelegate {
  441. func sendVoice(path: String, voice: Data, duration: String) {
  442. let msg = IMMessageBodyInfo()
  443. msg.fileTempPath = path
  444. msg.body = o2_im_msg_body_audio
  445. msg.type = o2_im_msg_type_audio
  446. msg.audioDuration = duration
  447. let msgId = self.prepareForSendFileMsg(tempMessage: msg)
  448. let fileName = path.split("/").last ?? "MySound.ilbc"
  449. DDLogDebug("音频文件:\(fileName)")
  450. self.uploadFileAndSendMsg(messageId: msgId, data: voice, fileName: fileName, type: o2_im_msg_type_audio)
  451. }
  452. }
  453. // MARK: - 拍照delegate
  454. extension IMChatViewController: UIImagePickerControllerDelegate & UINavigationControllerDelegate {
  455. func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey: Any]) {
  456. if let image = info[.editedImage] as? UIImage {
  457. let fileName = "\(UUID().uuidString).png"
  458. let newData = image.pngData()!
  459. let localFilePath = self.storageLocalImage(imageData: newData, fileName: fileName)
  460. let msgId = self.prepareForSendImageMsg(filePath: localFilePath)
  461. self.uploadFileAndSendMsg(messageId: msgId, data: newData, fileName: fileName, type: o2_im_msg_type_image)
  462. } else {
  463. DDLogError("没有选择到图片!")
  464. }
  465. picker.dismiss(animated: true, completion: nil)
  466. // var newData = data
  467. // //处理图片旋转的问题
  468. // if imageOrientation != UIImage.Orientation.up {
  469. // let newImage = UIImage(data: data)?.fixOrientation()
  470. // if newImage != nil {
  471. // newData = newImage!.pngData()!
  472. // }
  473. // }
  474. // var fileName = ""
  475. // if dict?["PHImageFileURLKey"] != nil {
  476. // let fileURL = dict?["PHImageFileURLKey"] as! URL
  477. // fileName = fileURL.lastPathComponent
  478. // } else {
  479. // fileName = "\(UUID().uuidString).png"
  480. // }
  481. }
  482. }
  483. // MARK: - 图片消息点击 delegate
  484. extension IMChatViewController: IMChatMessageDelegate {
  485. func openApplication(storyboard: String) {
  486. if storyboard == "mind" {
  487. let flutterViewController = O2FlutterViewController()
  488. flutterViewController.setInitialRoute("mindMap")
  489. self.present(flutterViewController, animated: false, completion: nil)
  490. }else {
  491. let storyBoard = UIStoryboard(name: storyboard, bundle: nil)
  492. guard let destVC = storyBoard.instantiateInitialViewController() else {
  493. return
  494. }
  495. destVC.modalPresentationStyle = .fullScreen
  496. if destVC.isKind(of: ZLNavigationController.self) {
  497. self.show(destVC, sender: nil)
  498. }else{
  499. self.navigationController?.pushViewController(destVC, animated: true)
  500. }
  501. }
  502. }
  503. func openWork(workId: String) {
  504. let storyBoard = UIStoryboard(name: "task", bundle: nil)
  505. let destVC = storyBoard.instantiateViewController(withIdentifier: "todoTaskDetailVC") as! TodoTaskDetailViewController
  506. let json = """
  507. {"work":"\(workId)", "workCompleted":"", "title":""}
  508. """
  509. let todo = TodoTask(JSONString: json)
  510. destVC.todoTask = todo
  511. destVC.backFlag = 3 //隐藏就行
  512. self.show(destVC, sender: nil)
  513. }
  514. func openLocatinMap(info: IMMessageBodyInfo) {
  515. let map = IMShowLocationViewController()
  516. map.address = info.address
  517. map.addressDetail = info.addressDetail
  518. map.latitude = info.latitude
  519. map.longitude = info.longitude
  520. self.navigationController?.pushViewController(map, animated: false)
  521. }
  522. func clickImageMessage(info: IMMessageBodyInfo) {
  523. if let id = info.fileId {
  524. self.showLoading()
  525. var ext = info.fileExtension ?? "png"
  526. if ext.isEmpty {
  527. ext = "png"
  528. }
  529. O2IMFileManager.shared
  530. .getFileLocalUrl(fileId: id, fileExtension: ext)
  531. .always {
  532. self.hideLoading()
  533. }.then { (path) in
  534. let currentURL = NSURL(fileURLWithPath: path.path)
  535. DDLogDebug(currentURL.description)
  536. DDLogDebug(path.path)
  537. if QLPreviewController.canPreview(currentURL) {
  538. self.previewVC.currentFileURLS.removeAll()
  539. self.previewVC.currentFileURLS.append(currentURL)
  540. self.previewVC.reloadData()
  541. self.pushVC(self.previewVC)
  542. } else {
  543. self.showError(title: "当前文件类型不支持预览!")
  544. }
  545. }
  546. .catch { (error) in
  547. DDLogError(error.localizedDescription)
  548. self.showError(title: "获取文件异常!")
  549. }
  550. } else if let temp = info.fileTempPath {
  551. let currentURL = NSURL(fileURLWithPath: temp)
  552. DDLogDebug(currentURL.description)
  553. DDLogDebug(temp)
  554. if QLPreviewController.canPreview(currentURL) {
  555. self.previewVC.currentFileURLS.removeAll()
  556. self.previewVC.currentFileURLS.append(currentURL)
  557. self.previewVC.reloadData()
  558. self.pushVC(self.previewVC)
  559. } else {
  560. self.showError(title: "当前文件类型不支持预览!")
  561. }
  562. }
  563. }
  564. }
  565. // MARK: - 表情点击 delegate
  566. extension IMChatViewController: IMChatEmojiBarClickDelegate {
  567. func clickEmoji(emoji: String) {
  568. DDLogDebug("发送表情消息 \(emoji)")
  569. self.sendEmojiMessage(emoji: emoji)
  570. }
  571. }
  572. // MARK: - tableview delegate
  573. extension IMChatViewController: UITableViewDelegate, UITableViewDataSource {
  574. func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
  575. return self.chatMessageList.count
  576. }
  577. func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
  578. let msg = self.chatMessageList[indexPath.row]
  579. if msg.createPerson == O2AuthSDK.shared.myInfo()?.distinguishedName { //发送者
  580. if let cell = tableView.dequeueReusableCell(withIdentifier: "IMChatMessageSendViewCell", for: indexPath) as? IMChatMessageSendViewCell {
  581. cell.setContent(item: self.chatMessageList[indexPath.row])
  582. cell.delegate = self
  583. return cell
  584. }
  585. } else {
  586. if let cell = tableView.dequeueReusableCell(withIdentifier: "IMChatMessageViewCell", for: indexPath) as? IMChatMessageViewCell {
  587. cell.setContent(item: self.chatMessageList[indexPath.row])
  588. cell.delegate = self
  589. return cell
  590. }
  591. }
  592. return UITableViewCell()
  593. }
  594. func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
  595. let msg = self.chatMessageList[indexPath.row]
  596. return cellHeight(item: msg)
  597. }
  598. func cellHeight(item: IMMessageInfo) -> CGFloat {
  599. if let jsonBody = item.body, let body = IMMessageBodyInfo.deserialize(from: jsonBody){
  600. if body.type == o2_im_msg_type_emoji {
  601. // 上边距 69 + emoji高度 + 内边距 + 底部空白高度
  602. return 69 + 36 + 20 + 10
  603. } else if body.type == o2_im_msg_type_image {
  604. // 上边距 69 + 图片高度 + 内边距 + 底部空白高度
  605. return 69 + 192 + 20 + 10
  606. } else if o2_im_msg_type_audio == body.type {
  607. // 上边距 69 + audio高度 + 内边距 + 底部空白高度
  608. return 69 + IMAudioView.IMAudioView_height + 20 + 10
  609. } else if o2_im_msg_type_location == body.type {
  610. // 上边距 69 + 位置图高度 + 内边距 + 底部空白高度
  611. return 69 + IMLocationView.IMLocationViewHeight + 20 + 10
  612. } else {
  613. let size = body.body!.getSizeWithMaxWidth(fontSize: 16, maxWidth: messageWidth)
  614. // 上边距 69 + 文字高度 + 内边距 + 底部空白高度
  615. return 69 + size.height + 28 + 10
  616. }
  617. }
  618. return 132
  619. }
  620. func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
  621. tableView.deselectRow(at: indexPath, animated: false)
  622. }
  623. }
  624. // MARK: - textField delegate
  625. extension IMChatViewController: UITextFieldDelegate {
  626. func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
  627. DDLogDebug("准备开始输入......")
  628. closeOtherView()
  629. return true
  630. }
  631. private func closeOtherView() {
  632. self.isShowEmoji = false
  633. self.isShowAudioView = false
  634. self.bottomBarHeightConstraint.constant = self.bottomBarHeight.toCGFloat
  635. self.view.layoutIfNeeded()
  636. }
  637. func textFieldShouldReturn(_ textField: UITextField) -> Bool {
  638. DDLogDebug("回车。。。。")
  639. self.sendTextMessage()
  640. return true
  641. }
  642. }