IMChatViewController.swift 26 KB

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