IMChatViewController.swift 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910
  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 BSImagePicker
  11. import Photos
  12. import Alamofire
  13. import AlamofireImage
  14. import SwiftyJSON
  15. import QuickLook
  16. import SnapKit
  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. //录音的时候显示的view
  42. private var voiceIconImage: UIImageView?
  43. private var voiceIocnTitleLable: UILabel?
  44. private var voiceImageSuperView: UIView?
  45. //预览文件
  46. private lazy var previewVC: CloudFilePreviewController = {
  47. return CloudFilePreviewController()
  48. }()
  49. private lazy var viewModel: IMViewModel = {
  50. return IMViewModel()
  51. }()
  52. // MARK: - properties
  53. var conversation: IMConversationInfo? = nil
  54. //private
  55. private var chatMessageList: [IMMessageInfo] = []
  56. private var page = 0
  57. private var isShowEmoji = false
  58. private var isShowAudioView = false
  59. private var bottomBarHeight = 64 //底部输入框 表情按钮 的高度
  60. private let bottomToolbarHeight = 46 //底部工具栏 麦克风 相册 相机等按钮的位置
  61. private var playingAudioMessageId: String? // 正在播放音频的消息id
  62. deinit {
  63. AudioPlayerManager.shared.delegate = nil
  64. }
  65. // MARK: - functions
  66. override func viewDidLoad() {
  67. super.viewDidLoad()
  68. self.tableView.delegate = self
  69. self.tableView.dataSource = self
  70. self.tableView.register(UINib(nibName: "IMChatMessageViewCell", bundle: nil), forCellReuseIdentifier: "IMChatMessageViewCell")
  71. self.tableView.register(UINib(nibName: "IMChatMessageSendViewCell", bundle: nil), forCellReuseIdentifier: "IMChatMessageSendViewCell")
  72. self.tableView.separatorStyle = .none
  73. // self.tableView.rowHeight = UITableView.automaticDimension
  74. // self.tableView.estimatedRowHeight = 144
  75. self.tableView.backgroundColor = UIColor(hex: "#f3f3f3")
  76. self.tableView.mj_header = MJRefreshNormalHeader(refreshingBlock: {
  77. self.loadMsgList()
  78. })
  79. // 输入框 delegate
  80. self.messageInputView.delegate = self
  81. // 播放audio delegate
  82. AudioPlayerManager.shared.delegate = self
  83. //底部安全距离 老机型没有
  84. self.bottomBarHeight = Int(iPhoneX ? 64 + IPHONEX_BOTTOM_SAFE_HEIGHT: 64) + self.bottomToolbarHeight
  85. self.bottomBarHeightConstraint.constant = self.bottomBarHeight.toCGFloat
  86. self.bottomBar.topBorder(width: 1, borderColor: base_gray_color.alpha(0.5))
  87. self.messageInputView.backgroundColor = base_gray_color
  88. //标题
  89. if self.conversation?.type == o2_im_conversation_type_single {
  90. if let c = self.conversation {
  91. var person = ""
  92. c.personList?.forEach({ (p) in
  93. if p != O2AuthSDK.shared.myInfo()?.distinguishedName {
  94. person = p
  95. }
  96. })
  97. if !person.isEmpty {
  98. self.title = person.split("@").first ?? ""
  99. }
  100. }
  101. } else {
  102. self.title = self.conversation?.title
  103. }
  104. //群会话 添加修改标题的按钮
  105. if self.conversation?.type == o2_im_conversation_type_group &&
  106. O2AuthSDK.shared.myInfo()?.distinguishedName == self.conversation?.adminPerson {
  107. navigationItem.rightBarButtonItem = UIBarButtonItem(title: "修改", style: .plain, target: self, action: #selector(clickUpdate))
  108. }
  109. //获取聊天数据
  110. self.loadMsgList()
  111. //阅读
  112. self.viewModel.readConversation(conversationId: self.conversation?.id)
  113. }
  114. override func viewWillAppear(_ animated: Bool) {
  115. NotificationCenter.default.addObserver(self, selector: #selector(receiveMessageFromWs(notice:)), name: OONotification.websocket.notificationName, object: nil)
  116. }
  117. override func viewWillDisappear(_ animated: Bool) {
  118. NotificationCenter.default.removeObserver(self)
  119. }
  120. @objc private func receiveMessageFromWs(notice: Notification) {
  121. DDLogDebug("接收到websocket im 消息")
  122. if let message = notice.object as? IMMessageInfo {
  123. if message.conversationId == self.conversation?.id {
  124. self.chatMessageList.append(message)
  125. self.scrollMessageToBottom()
  126. self.viewModel.readConversation(conversationId: self.conversation?.id)
  127. }
  128. }
  129. }
  130. @objc private func clickUpdate() {
  131. self.showSheetAction(title: "", message: "选择要修改的项", actions: [
  132. UIAlertAction(title: "修改群名", style: .default, handler: { (action) in
  133. self.updateTitle()
  134. }),
  135. UIAlertAction(title: "修改成员", style: .default, handler: { (action) in
  136. self.updatePeople()
  137. })
  138. ])
  139. }
  140. private func updateTitle() {
  141. self.showPromptAlert(title: "", message: "修改群名", inputText: "") { (action, result) in
  142. if result.isEmpty {
  143. self.showError(title: "请输入群名")
  144. }else {
  145. self.showLoading()
  146. self.viewModel.updateConversationTitle(id: (self.conversation?.id!)!, title: result)
  147. .then { (c) in
  148. self.title = result
  149. self.conversation?.title = result
  150. self.showSuccess(title: "修改成功")
  151. }.catch { (err) in
  152. DDLogError(err.localizedDescription)
  153. self.showError(title: "修改失败")
  154. }
  155. }
  156. }
  157. }
  158. private func updatePeople() {
  159. //选择人员 反选已经存在的成员
  160. if let users = self.conversation?.personList {
  161. self.showContactPicker(modes: [.person], callback: { (result) in
  162. if let people = result.users {
  163. if people.count >= 3 {
  164. var peopleDNs: [String] = []
  165. var containMe = false
  166. people.forEach { (item) in
  167. peopleDNs.append(item.distinguishedName!)
  168. if O2AuthSDK.shared.myInfo()?.distinguishedName == item.distinguishedName {
  169. containMe = true
  170. }
  171. }
  172. if !containMe {
  173. peopleDNs.append((O2AuthSDK.shared.myInfo()?.distinguishedName)!)
  174. }
  175. self.showLoading()
  176. self.viewModel.updateConversationPeople(id: (self.conversation?.id!)!, users: peopleDNs)
  177. .then { (c) in
  178. self.conversation?.personList = peopleDNs
  179. self.showSuccess(title: "修改成功")
  180. }.catch { (err) in
  181. DDLogError(err.localizedDescription)
  182. self.showError(title: "修改失败")
  183. }
  184. }else {
  185. self.showError(title: "选择人数不足3人")
  186. }
  187. }else {
  188. self.showError(title: "请选择人员")
  189. }
  190. }, initUserPickedArray: users)
  191. }else {
  192. self.showError(title: "成员列表数据错误!")
  193. }
  194. }
  195. //获取消息
  196. private func loadMsgList() {
  197. if let c = self.conversation, let id = c.id {
  198. self.viewModel.myMsgPageList(page: self.page + 1, conversationId: id).then { (list) in
  199. if !list.isEmpty {
  200. self.page += 1
  201. self.chatMessageList.insert(contentsOf: list, at: 0)
  202. if self.page == 1 {
  203. self.scrollMessageToBottom()
  204. }else {
  205. DispatchQueue.main.async {
  206. self.tableView.reloadData()
  207. }
  208. }
  209. }
  210. if self.tableView.mj_header.isRefreshing(){
  211. self.tableView.mj_header.endRefreshing()
  212. }
  213. }.catch { (error) in
  214. DDLogError(error.localizedDescription)
  215. if self.tableView.mj_header.isRefreshing(){
  216. self.tableView.mj_header.endRefreshing()
  217. }
  218. }
  219. } else {
  220. self.showError(title: "参数错误!!!")
  221. }
  222. }
  223. //刷新tableview 滚动到底部
  224. private func scrollMessageToBottom() {
  225. DispatchQueue.main.async {
  226. self.tableView.reloadData()
  227. if self.chatMessageList.count > 0 {
  228. self.tableView.scrollToRow(at: IndexPath(row: self.chatMessageList.count - 1, section: 0), at: .bottom, animated: false)
  229. }
  230. }
  231. }
  232. //发送文本消息
  233. private func sendTextMessage() {
  234. guard let msg = self.messageInputView.text else {
  235. return
  236. }
  237. self.messageInputView.text = ""
  238. let body = IMMessageBodyInfo()
  239. body.type = o2_im_msg_type_text
  240. body.body = msg
  241. sendMessage(body: body)
  242. }
  243. //发送表情消息
  244. private func sendEmojiMessage(emoji: String) {
  245. let body = IMMessageBodyInfo()
  246. body.type = o2_im_msg_type_emoji
  247. body.body = emoji
  248. sendMessage(body: body)
  249. }
  250. //发送地图消息消息
  251. private func sendLocationMessage(loc: O2LocationData) {
  252. let body = IMMessageBodyInfo()
  253. body.type = o2_im_msg_type_location
  254. body.body = o2_im_msg_body_location
  255. body.address = loc.address
  256. body.addressDetail = loc.addressDetail
  257. body.longitude = loc.longitude
  258. body.latitude = loc.latitude
  259. sendMessage(body: body)
  260. }
  261. //发送消息到服务器
  262. private func sendMessage(body: IMMessageBodyInfo) {
  263. let message = IMMessageInfo()
  264. message.body = body.toJSONString()
  265. message.id = UUID().uuidString
  266. message.conversationId = self.conversation?.id
  267. message.createPerson = O2AuthSDK.shared.myInfo()?.distinguishedName
  268. message.createTime = Date().formatterDate(formatter: "yyyy-MM-dd HH:mm:ss")
  269. //添加到界面
  270. self.chatMessageList.append(message)
  271. self.scrollMessageToBottom()
  272. //发送消息到服务器
  273. self.viewModel.sendMsg(msg: message)
  274. .then { (result) in
  275. DDLogDebug("发送消息成功 \(result)")
  276. self.viewModel.readConversation(conversationId: self.conversation?.id)
  277. }.catch { (error) in
  278. DDLogError(error.localizedDescription)
  279. self.showError(title: "发送消息失败!")
  280. }
  281. }
  282. //选择照片
  283. private func chooseImage() {
  284. self.choosePhotoWithImagePicker { (fileName, newData) in
  285. let localFilePath = self.storageLocalImage(imageData: newData, fileName: fileName)
  286. let msgId = self.prepareForSendImageMsg(filePath: localFilePath)
  287. self.uploadFileAndSendMsg(messageId: msgId, data: newData, fileName: fileName, type: o2_im_msg_type_image)
  288. }
  289. }
  290. //临时存储本地
  291. private func storageLocalImage(imageData: Data, fileName: String) -> String {
  292. let fileTempPath = FileUtil.share.cacheDir().appendingPathComponent(fileName)
  293. do {
  294. try imageData.write(to: fileTempPath)
  295. return fileTempPath.path
  296. } catch {
  297. print(error.localizedDescription)
  298. return fileTempPath.path
  299. }
  300. }
  301. //发送消息前 先载入界面
  302. private func prepareForSendImageMsg(filePath: String) -> String {
  303. let body = IMMessageBodyInfo()
  304. body.type = o2_im_msg_type_image
  305. body.body = o2_im_msg_body_image
  306. body.fileTempPath = filePath
  307. let message = IMMessageInfo()
  308. let msgId = UUID().uuidString
  309. message.body = body.toJSONString()
  310. message.id = msgId
  311. message.conversationId = self.conversation?.id
  312. message.createPerson = O2AuthSDK.shared.myInfo()?.distinguishedName
  313. message.createTime = Date().formatterDate(formatter: "yyyy-MM-dd HH:mm:ss")
  314. //添加到界面
  315. self.chatMessageList.append(message)
  316. self.scrollMessageToBottom()
  317. return msgId
  318. }
  319. private func prepareForSendFileMsg(filePath: String) -> String {
  320. let body = IMMessageBodyInfo()
  321. body.type = o2_im_msg_type_file
  322. body.body = o2_im_msg_body_file
  323. body.fileTempPath = filePath
  324. let message = IMMessageInfo()
  325. let msgId = UUID().uuidString
  326. message.body = body.toJSONString()
  327. message.id = msgId
  328. message.conversationId = self.conversation?.id
  329. message.createPerson = O2AuthSDK.shared.myInfo()?.distinguishedName
  330. message.createTime = Date().formatterDate(formatter: "yyyy-MM-dd HH:mm:ss")
  331. //添加到界面
  332. self.chatMessageList.append(message)
  333. self.scrollMessageToBottom()
  334. return msgId
  335. }
  336. //发送消息前 先载入界面
  337. private func prepareForSendAudioMsg(tempMessage: IMMessageBodyInfo) -> String {
  338. let message = IMMessageInfo()
  339. let msgId = UUID().uuidString
  340. message.body = tempMessage.toJSONString()
  341. message.id = msgId
  342. message.conversationId = self.conversation?.id
  343. message.createPerson = O2AuthSDK.shared.myInfo()?.distinguishedName
  344. message.createTime = Date().formatterDate(formatter: "yyyy-MM-dd HH:mm:ss")
  345. //添加到界面
  346. self.chatMessageList.append(message)
  347. self.scrollMessageToBottom()
  348. return msgId
  349. }
  350. //上传图片 音频 文档 等文件到服务器并发送消息
  351. private func uploadFileAndSendMsg(messageId: String, data: Data, fileName: String, type: String) {
  352. guard let cId = self.conversation?.id else {
  353. return
  354. }
  355. self.viewModel.uploadFile(conversationId: cId, type: type, fileName: fileName, file: data).then { back in
  356. DDLogDebug("上传文件成功")
  357. guard let message = self.chatMessageList.first (where: { (info) -> Bool in
  358. return info.id == messageId
  359. }) else {
  360. DDLogDebug("没有找到对应的消息")
  361. return
  362. }
  363. let body = IMMessageBodyInfo.deserialize(from: message.body)
  364. body?.fileId = back.id
  365. body?.fileExtension = back.fileExtension
  366. body?.fileName = back.fileName
  367. body?.fileTempPath = nil
  368. message.body = body?.toJSONString()
  369. //发送消息到服务器
  370. self.viewModel.sendMsg(msg: message)
  371. .then { (result) in
  372. DDLogDebug("消息 发送成功 \(result)")
  373. self.viewModel.readConversation(conversationId: self.conversation?.id)
  374. }.catch { (error) in
  375. DDLogError(error.localizedDescription)
  376. self.showError(title: "发送消息失败!")
  377. }
  378. }.catch { err in
  379. self.showError(title: "上传错误,\(err.localizedDescription)")
  380. }
  381. }
  382. // 选择外部文件
  383. private func chooseFile() {
  384. let documentTypes = ["public.content",
  385. "public.text",
  386. "public.source-code",
  387. "public.image",
  388. "public.audiovisual-content",
  389. "com.adobe.pdf",
  390. "com.apple.keynote.key",
  391. "com.microsoft.word.doc",
  392. "com.microsoft.excel.xls",
  393. "com.microsoft.powerpoint.ppt"]
  394. let picker = UIDocumentPickerViewController(documentTypes: documentTypes, in: .open)
  395. picker.delegate = self
  396. self.present(picker, animated: true, completion: nil)
  397. }
  398. private func playAudioGif(id: String?) {
  399. self.playingAudioMessageId = id
  400. self.tableView.reloadData()
  401. }
  402. private func stopPlayAudioGif() {
  403. self.playingAudioMessageId = nil
  404. self.tableView.reloadData()
  405. }
  406. // 播放audio
  407. private func playAudio(url: URL) {
  408. do {
  409. let data = try Data(contentsOf: url)
  410. AudioPlayerManager.shared.managerAudioWithData(data, toplay: true)
  411. } catch {
  412. DDLogError(error.localizedDescription)
  413. }
  414. }
  415. // MARK: - IBAction
  416. //点击表情按钮
  417. @IBAction func clickEmojiBtn(_ sender: UIButton) {
  418. self.isShowEmoji.toggle()
  419. self.view.endEditing(true)
  420. if self.isShowEmoji {
  421. //audio view 先关闭
  422. self.isShowAudioView = false
  423. self.audioBtnView.removeFromSuperview()
  424. //开始添加emojiBar
  425. self.bottomBarHeightConstraint.constant = self.bottomBarHeight.toCGFloat + self.emojiBarHeight.toCGFloat
  426. self.emojiBar.delegate = self
  427. self.emojiBar.translatesAutoresizingMaskIntoConstraints = false
  428. self.bottomBar.addSubview(self.emojiBar)
  429. let top = NSLayoutConstraint(item: self.emojiBar, attribute: .top, relatedBy: .equal, toItem: self.emojiBar.superview!, attribute: .top, multiplier: 1, constant: CGFloat(self.bottomBarHeight))
  430. let width = NSLayoutConstraint(item: self.emojiBar, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: SCREEN_WIDTH)
  431. let height = NSLayoutConstraint(item: self.emojiBar, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: self.emojiBarHeight.toCGFloat)
  432. NSLayoutConstraint.activate([top, width, height])
  433. } else {
  434. self.bottomBarHeightConstraint.constant = self.bottomBarHeight.toCGFloat
  435. self.emojiBar.removeFromSuperview()
  436. }
  437. self.view.layoutIfNeeded()
  438. }
  439. @IBAction func micBtnClick(_ sender: UIButton) {
  440. DDLogDebug("点击了麦克风按钮")
  441. self.isShowAudioView.toggle()
  442. self.view.endEditing(true)
  443. if self.isShowAudioView {
  444. //emoji view 先关闭
  445. self.isShowEmoji = false
  446. self.emojiBar.removeFromSuperview()
  447. //开始添加emojiBar
  448. self.bottomBarHeightConstraint.constant = self.bottomBarHeight.toCGFloat + self.emojiBarHeight.toCGFloat
  449. self.audioBtnView.translatesAutoresizingMaskIntoConstraints = false
  450. self.bottomBar.addSubview(self.audioBtnView)
  451. let top = NSLayoutConstraint(item: self.audioBtnView, attribute: .top, relatedBy: .equal, toItem: self.audioBtnView.superview!, attribute: .top, multiplier: 1, constant: CGFloat(self.bottomBarHeight))
  452. let width = NSLayoutConstraint(item: self.audioBtnView, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: SCREEN_WIDTH)
  453. let height = NSLayoutConstraint(item: self.audioBtnView, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: self.emojiBarHeight.toCGFloat)
  454. NSLayoutConstraint.activate([top, width, height])
  455. } else {
  456. self.bottomBarHeightConstraint.constant = self.bottomBarHeight.toCGFloat
  457. self.audioBtnView.removeFromSuperview()
  458. }
  459. self.view.layoutIfNeeded()
  460. }
  461. @IBAction func imgBtnClick(_ sender: UIButton) {
  462. DDLogDebug("点击了图片按钮")
  463. self.chooseImage()
  464. }
  465. @IBAction func cameraBtnClick(_ sender: UIButton) {
  466. DDLogDebug("点击了相机按钮")
  467. self.takePhoto(delegate: self)
  468. }
  469. @IBAction func locationBtnClick(_ sender: UIButton) {
  470. DDLogDebug("点击了位置按钮")
  471. let vc = IMLocationChooseController.openChooseLocation { (data) in
  472. self.sendLocationMessage(loc: data)
  473. }
  474. self.navigationController?.pushViewController(vc, animated: false)
  475. }
  476. @IBAction func fileBtnClick(_ sender: UIButton) {
  477. DDLogDebug("点击了文件按钮")
  478. self.chooseFile()
  479. }
  480. }
  481. // MARK: - 外部文件选择代理
  482. extension IMChatViewController: UIDocumentPickerDelegate {
  483. func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
  484. if urls.count > 0 {
  485. let file = urls[0]
  486. if file.startAccessingSecurityScopedResource() { //访问权限
  487. let fileName = file.lastPathComponent
  488. if let data = try? Data(contentsOf: file) {
  489. let fileext = file.pathExtension
  490. if O2.isImageExt(fileext) { // 图片消息
  491. let localFilePath = self.storageLocalImage(imageData: data, fileName: fileName)
  492. let msgId = self.prepareForSendImageMsg(filePath: localFilePath)
  493. self.uploadFileAndSendMsg(messageId: msgId, data: data, fileName: fileName, type: o2_im_msg_type_image)
  494. }else { // 文件消息
  495. let localFilePath = self.storageLocalImage(imageData: data, fileName: fileName)
  496. let msgId = self.prepareForSendFileMsg(filePath: localFilePath)
  497. self.uploadFileAndSendMsg(messageId: msgId, data: data, fileName: fileName, type: o2_im_msg_type_file)
  498. }
  499. } else {
  500. self.showError(title: "读取文件失败")
  501. }
  502. } else {
  503. self.showError(title: "没有获取文件的权限")
  504. }
  505. }
  506. }
  507. }
  508. // MARK: - 录音delegate
  509. extension IMChatViewController: IMChatAudioViewDelegate {
  510. private func audioRecordingGif() -> UIImage? {
  511. let url: URL? = Bundle.main.url(forResource: "listener08_anim", withExtension: "gif")
  512. guard let u = url else {
  513. return nil
  514. }
  515. guard let data = try? Data.init(contentsOf: u) else {
  516. return nil
  517. }
  518. return UIImage.sd_animatedGIF(with: data)
  519. }
  520. func showAudioRecordingView() {
  521. if self.voiceIconImage == nil {
  522. self.voiceImageSuperView = UIView()
  523. self.view.addSubview(self.voiceImageSuperView!)
  524. self.voiceImageSuperView?.backgroundColor = UIColor(displayP3Red: 0, green: 0, blue: 0, alpha: 0.6)
  525. self.voiceImageSuperView?.snp_makeConstraints { (make) in
  526. make.center.equalTo(self.view)
  527. make.size.equalTo(CGSize(width:140, height:140))
  528. }
  529. self.voiceIconImage = UIImageView()
  530. self.voiceImageSuperView?.addSubview(self.voiceIconImage!)
  531. self.voiceIconImage?.snp_makeConstraints { (make) in
  532. make.top.left.equalTo(self.voiceImageSuperView!).inset(UIEdgeInsets(top: 20, left: 35, bottom: 0, right: 0))
  533. make.size.equalTo(CGSize(width: 70, height: 70))
  534. }
  535. let voiceIconTitleLabel = UILabel()
  536. self.voiceIocnTitleLable = voiceIconTitleLabel
  537. self.voiceIconImage?.addSubview(voiceIconTitleLabel)
  538. voiceIconTitleLabel.textColor = UIColor.white
  539. voiceIconTitleLabel.font = .systemFont(ofSize: 12)
  540. voiceIconTitleLabel.text = "松开发送,上滑取消"
  541. voiceIconTitleLabel.snp_makeConstraints { (make) in
  542. make.bottom.equalTo(self.voiceImageSuperView!).offset(-15)
  543. make.centerX.equalTo(self.voiceImageSuperView!)
  544. }
  545. }
  546. self.voiceImageSuperView?.isHidden = false
  547. if let gifImage = self.audioRecordingGif() {
  548. self.voiceIconImage?.image = gifImage
  549. }else {
  550. self.voiceIconImage?.image = UIImage(named: "chat_audio_voice")
  551. }
  552. self.voiceIocnTitleLable?.text = "松开发送,上滑取消";
  553. }
  554. func hideAudioRecordingView() {
  555. self.voiceImageSuperView?.isHidden = true
  556. }
  557. func changeRecordingView2uplide() {
  558. self.voiceIocnTitleLable?.text = "松开手指,取消发送";
  559. self.voiceIconImage?.image = UIImage(named: "chat_audio_cancel")
  560. }
  561. func changeRecordingView2down() {
  562. if let gifImage = self.audioRecordingGif() {
  563. self.voiceIconImage?.image = gifImage
  564. }else {
  565. self.voiceIconImage?.image = UIImage(named: "chat_audio_voice")
  566. }
  567. self.voiceIocnTitleLable?.text = "松开发送,上滑取消";
  568. }
  569. func sendVoice(path: String, voice: Data, duration: String) {
  570. let msg = IMMessageBodyInfo()
  571. msg.fileTempPath = path
  572. msg.body = o2_im_msg_body_audio
  573. msg.type = o2_im_msg_type_audio
  574. msg.audioDuration = duration
  575. let msgId = self.prepareForSendAudioMsg(tempMessage: msg)
  576. let fileName = path.split("/").last ?? "MySound.ilbc"
  577. DDLogDebug("音频文件:\(fileName)")
  578. self.uploadFileAndSendMsg(messageId: msgId, data: voice, fileName: fileName, type: o2_im_msg_type_audio)
  579. }
  580. }
  581. // MARK: - 拍照delegate
  582. extension IMChatViewController: UIImagePickerControllerDelegate & UINavigationControllerDelegate {
  583. func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey: Any]) {
  584. if let image = info[.editedImage] as? UIImage {
  585. let fileName = "\(UUID().uuidString).png"
  586. let newData = image.pngData()!
  587. let localFilePath = self.storageLocalImage(imageData: newData, fileName: fileName)
  588. let msgId = self.prepareForSendImageMsg(filePath: localFilePath)
  589. self.uploadFileAndSendMsg(messageId: msgId, data: newData, fileName: fileName, type: o2_im_msg_type_image)
  590. } else {
  591. DDLogError("没有选择到图片!")
  592. }
  593. picker.dismiss(animated: true, completion: nil)
  594. // var newData = data
  595. // //处理图片旋转的问题
  596. // if imageOrientation != UIImage.Orientation.up {
  597. // let newImage = UIImage(data: data)?.fixOrientation()
  598. // if newImage != nil {
  599. // newData = newImage!.pngData()!
  600. // }
  601. // }
  602. // var fileName = ""
  603. // if dict?["PHImageFileURLKey"] != nil {
  604. // let fileURL = dict?["PHImageFileURLKey"] as! URL
  605. // fileName = fileURL.lastPathComponent
  606. // } else {
  607. // fileName = "\(UUID().uuidString).png"
  608. // }
  609. }
  610. }
  611. // MARK: - audio 播放 delegate
  612. extension IMChatViewController: AudioPlayerManagerDelegate {
  613. func didAudioPlayerBeginPlay(_ AudioPlayer: AVAudioPlayer) {
  614. DDLogDebug("播放开始")
  615. }
  616. func didAudioPlayerStopPlay(_ AudioPlayer: AVAudioPlayer) {
  617. DDLogDebug("播放结束")
  618. self.stopPlayAudioGif()
  619. }
  620. func didAudioPlayerPausePlay(_ AudioPlayer: AVAudioPlayer) {
  621. DDLogDebug("播放暂停")
  622. }
  623. }
  624. // MARK: - 消息点击 delegate
  625. extension IMChatViewController: IMChatMessageDelegate {
  626. func openApplication(storyboard: String) {
  627. if storyboard == "mind" {
  628. let flutterViewController = O2FlutterViewController()
  629. flutterViewController.setInitialRoute("mindMap")
  630. flutterViewController.modalPresentationStyle = .fullScreen
  631. self.present(flutterViewController, animated: false, completion: nil)
  632. }else {
  633. let storyBoard = UIStoryboard(name: storyboard, bundle: nil)
  634. guard let destVC = storyBoard.instantiateInitialViewController() else {
  635. return
  636. }
  637. destVC.modalPresentationStyle = .fullScreen
  638. if destVC.isKind(of: ZLNavigationController.self) {
  639. self.show(destVC, sender: nil)
  640. }else{
  641. self.navigationController?.pushViewController(destVC, animated: true)
  642. }
  643. }
  644. }
  645. func openWork(workId: String) {
  646. self.showLoading()
  647. self.viewModel.isWorkCompleted(work: workId).always {
  648. self.hideLoading()
  649. }.then{ result in
  650. if result {
  651. self.showMessage(msg: "工作已经完成了!")
  652. }else {
  653. self.openWorkPage(work: workId)
  654. }
  655. }.catch {_ in
  656. self.showMessage(msg: "工作已经完成了!")
  657. }
  658. }
  659. private func openWorkPage(work: String) {
  660. let storyBoard = UIStoryboard(name: "task", bundle: nil)
  661. let destVC = storyBoard.instantiateViewController(withIdentifier: "todoTaskDetailVC") as! TodoTaskDetailViewController
  662. let json = """
  663. {"work":"\(work)", "workCompleted":"", "title":""}
  664. """
  665. let todo = TodoTask(JSONString: json)
  666. destVC.todoTask = todo
  667. destVC.backFlag = 3 //隐藏就行
  668. self.show(destVC, sender: nil)
  669. }
  670. func openLocatinMap(info: IMMessageBodyInfo) {
  671. IMShowLocationViewController.pushShowLocation(vc: self, latitude: info.latitude, longitude: info.longitude,
  672. address: info.address, addressDetail: info.addressDetail)
  673. }
  674. func openImageOrFileMessage(info: IMMessageBodyInfo) {
  675. if let id = info.fileId {
  676. self.showLoading()
  677. var ext = info.fileExtension ?? "png"
  678. if ext.isEmpty {
  679. ext = "png"
  680. }
  681. O2IMFileManager.shared
  682. .getFileLocalUrl(fileId: id, fileExtension: ext)
  683. .always {
  684. self.hideLoading()
  685. }.then { (path) in
  686. let currentURL = NSURL(fileURLWithPath: path.path)
  687. DDLogDebug(currentURL.description)
  688. DDLogDebug(path.path)
  689. if QLPreviewController.canPreview(currentURL) {
  690. self.previewVC.currentFileURLS.removeAll()
  691. self.previewVC.currentFileURLS.append(currentURL)
  692. self.previewVC.reloadData()
  693. self.pushVC(self.previewVC)
  694. } else {
  695. self.showError(title: "当前文件类型不支持预览!")
  696. }
  697. }
  698. .catch { (error) in
  699. DDLogError(error.localizedDescription)
  700. self.showError(title: "获取文件异常!")
  701. }
  702. } else if let temp = info.fileTempPath {
  703. let currentURL = NSURL(fileURLWithPath: temp)
  704. DDLogDebug(currentURL.description)
  705. DDLogDebug(temp)
  706. if QLPreviewController.canPreview(currentURL) {
  707. self.previewVC.currentFileURLS.removeAll()
  708. self.previewVC.currentFileURLS.append(currentURL)
  709. self.previewVC.reloadData()
  710. self.pushVC(self.previewVC)
  711. } else {
  712. self.showError(title: "当前文件类型不支持预览!")
  713. }
  714. }
  715. }
  716. func playAudio(info: IMMessageBodyInfo, id: String?) {
  717. if self.playingAudioMessageId != nil && self.playingAudioMessageId == id {
  718. DDLogError("正在播放中。。。。。")
  719. return
  720. }
  721. if let fileId = info.fileId {
  722. var ext = info.fileExtension ?? "mp3"
  723. if ext.isEmpty {
  724. ext = "mp3"
  725. }
  726. O2IMFileManager.shared.getFileLocalUrl(fileId: fileId, fileExtension: ext)
  727. .then { (url) in
  728. self.playAudio(url: url)
  729. }.catch { (e) in
  730. DDLogError(e.localizedDescription)
  731. }
  732. } else if let filePath = info.fileTempPath {
  733. self.playAudio(url: URL(fileURLWithPath: filePath))
  734. }
  735. self.playAudioGif(id: id)
  736. }
  737. }
  738. // MARK: - 表情点击 delegate
  739. extension IMChatViewController: IMChatEmojiBarClickDelegate {
  740. func clickEmoji(emoji: String) {
  741. DDLogDebug("发送表情消息 \(emoji)")
  742. self.sendEmojiMessage(emoji: emoji)
  743. }
  744. }
  745. // MARK: - tableview delegate
  746. extension IMChatViewController: UITableViewDelegate, UITableViewDataSource {
  747. func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
  748. return self.chatMessageList.count
  749. }
  750. func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
  751. let msg = self.chatMessageList[indexPath.row]
  752. let isPlaying = self.playingAudioMessageId == nil ? false : (self.playingAudioMessageId == msg.id)
  753. if msg.createPerson == O2AuthSDK.shared.myInfo()?.distinguishedName { //发送者
  754. if let cell = tableView.dequeueReusableCell(withIdentifier: "IMChatMessageSendViewCell", for: indexPath) as? IMChatMessageSendViewCell {
  755. cell.setContent(item: self.chatMessageList[indexPath.row], isPlayingAudio: isPlaying)
  756. cell.delegate = self
  757. return cell
  758. }
  759. } else {
  760. if let cell = tableView.dequeueReusableCell(withIdentifier: "IMChatMessageViewCell", for: indexPath) as? IMChatMessageViewCell {
  761. cell.setContent(item: self.chatMessageList[indexPath.row], isPlayingAudio: isPlaying)
  762. cell.delegate = self
  763. return cell
  764. }
  765. }
  766. return UITableViewCell()
  767. }
  768. func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
  769. let msg = self.chatMessageList[indexPath.row]
  770. return cellHeight(item: msg)
  771. }
  772. func cellHeight(item: IMMessageInfo) -> CGFloat {
  773. if let jsonBody = item.body, let body = IMMessageBodyInfo.deserialize(from: jsonBody){
  774. if body.type == o2_im_msg_type_emoji {
  775. // 上边距 69 + emoji高度 + 内边距 + 底部空白高度
  776. return 69 + 36 + 20 + 10
  777. } else if body.type == o2_im_msg_type_image {
  778. // 上边距 69 + 图片高度 + 内边距 + 底部空白高度
  779. return 69 + 192 + 20 + 10
  780. } else if o2_im_msg_type_audio == body.type {
  781. // 上边距 69 + audio高度 + 内边距 + 底部空白高度
  782. return 69 + IMAudioView.IMAudioView_height + 20 + 10
  783. } else if o2_im_msg_type_location == body.type {
  784. // 上边距 69 + 位置图高度 + 内边距 + 底部空白高度
  785. return 69 + IMLocationView.IMLocationViewHeight + 20 + 10
  786. } else if o2_im_msg_type_file == body.type {
  787. return 69 + IMFileView.IMFileView_height + 20 + 10
  788. } else {
  789. let size = body.body!.getSizeWithMaxWidth(fontSize: 16, maxWidth: messageWidth)
  790. // 上边距 69 + 文字高度 + 内边距 + 底部空白高度
  791. return 69 + size.height + 28 + 10
  792. }
  793. }
  794. return 132
  795. }
  796. func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
  797. tableView.deselectRow(at: indexPath, animated: false)
  798. }
  799. }
  800. // MARK: - textField delegate
  801. extension IMChatViewController: UITextFieldDelegate {
  802. func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
  803. DDLogDebug("准备开始输入......")
  804. closeOtherView()
  805. return true
  806. }
  807. private func closeOtherView() {
  808. self.isShowEmoji = false
  809. self.isShowAudioView = false
  810. self.bottomBarHeightConstraint.constant = self.bottomBarHeight.toCGFloat
  811. self.view.layoutIfNeeded()
  812. }
  813. func textFieldShouldReturn(_ textField: UITextField) -> Bool {
  814. DDLogDebug("回车。。。。")
  815. self.sendTextMessage()
  816. return true
  817. }
  818. }