MessagesViewController.swift 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442
  1. /*
  2. MIT License
  3. Copyright (c) 2017-2019 MessageKit
  4. Permission is hereby granted, free of charge, to any person obtaining a copy
  5. of this software and associated documentation files (the "Software"), to deal
  6. in the Software without restriction, including without limitation the rights
  7. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. copies of the Software, and to permit persons to whom the Software is
  9. furnished to do so, subject to the following conditions:
  10. The above copyright notice and this permission notice shall be included in all
  11. copies or substantial portions of the Software.
  12. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  13. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  14. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  15. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  16. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  17. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  18. SOFTWARE.
  19. */
  20. import UIKit
  21. import InputBarAccessoryView
  22. /// A subclass of `UIViewController` with a `MessagesCollectionView` object
  23. /// that is used to display conversation interfaces.
  24. open class MessagesViewController: UIViewController,
  25. UICollectionViewDelegateFlowLayout, UICollectionViewDataSource {
  26. /// The `MessagesCollectionView` managed by the messages view controller object.
  27. open var messagesCollectionView = MessagesCollectionView()
  28. /// The `InputBarAccessoryView` used as the `inputAccessoryView` in the view controller.
  29. open var messageInputBar = InputBarAccessoryView()
  30. /// A Boolean value that determines whether the `MessagesCollectionView` scrolls to the
  31. /// bottom whenever the `InputTextView` begins editing.
  32. ///
  33. /// The default value of this property is `false`.
  34. open var scrollsToBottomOnKeyboardBeginsEditing: Bool = false
  35. /// A Boolean value that determines whether the `MessagesCollectionView`
  36. /// maintains it's current position when the height of the `MessageInputBar` changes.
  37. ///
  38. /// The default value of this property is `false`.
  39. open var maintainPositionOnKeyboardFrameChanged: Bool = false
  40. open override var canBecomeFirstResponder: Bool {
  41. return true
  42. }
  43. open override var inputAccessoryView: UIView? {
  44. return messageInputBar
  45. }
  46. open override var shouldAutorotate: Bool {
  47. return false
  48. }
  49. /// A CGFloat value that adds to (or, if negative, subtracts from) the automatically
  50. /// computed value of `messagesCollectionView.contentInset.bottom`. Meant to be used
  51. /// as a measure of last resort when the built-in algorithm does not produce the right
  52. /// value for your app. Please let us know when you end up having to use this property.
  53. open var additionalBottomInset: CGFloat = 0 {
  54. didSet {
  55. let delta = additionalBottomInset - oldValue
  56. messageCollectionViewBottomInset += delta
  57. }
  58. }
  59. public var isTypingIndicatorHidden: Bool {
  60. return messagesCollectionView.isTypingIndicatorHidden
  61. }
  62. public var selectedIndexPathForMenu: IndexPath?
  63. private var isFirstLayout: Bool = true
  64. internal var isMessagesControllerBeingDismissed: Bool = false
  65. internal var messageCollectionViewBottomInset: CGFloat = 0 {
  66. didSet {
  67. messagesCollectionView.contentInset.bottom = messageCollectionViewBottomInset
  68. messagesCollectionView.scrollIndicatorInsets.bottom = messageCollectionViewBottomInset
  69. }
  70. }
  71. // MARK: - View Life Cycle
  72. open override func viewDidLoad() {
  73. super.viewDidLoad()
  74. setupDefaults()
  75. setupSubviews()
  76. setupConstraints()
  77. setupDelegates()
  78. addMenuControllerObservers()
  79. addObservers()
  80. }
  81. open override func viewDidAppear(_ animated: Bool) {
  82. super.viewDidAppear(animated)
  83. isMessagesControllerBeingDismissed = false
  84. }
  85. open override func viewWillDisappear(_ animated: Bool) {
  86. super.viewWillDisappear(animated)
  87. isMessagesControllerBeingDismissed = true
  88. }
  89. open override func viewDidDisappear(_ animated: Bool) {
  90. super.viewDidDisappear(animated)
  91. isMessagesControllerBeingDismissed = false
  92. }
  93. open override func viewDidLayoutSubviews() {
  94. // Hack to prevent animation of the contentInset after viewDidAppear
  95. if isFirstLayout {
  96. defer { isFirstLayout = false }
  97. addKeyboardObservers()
  98. messageCollectionViewBottomInset = requiredInitialScrollViewBottomInset()
  99. }
  100. adjustScrollViewTopInset()
  101. }
  102. open override func viewSafeAreaInsetsDidChange() {
  103. if #available(iOS 11.0, *) {
  104. super.viewSafeAreaInsetsDidChange()
  105. }
  106. messageCollectionViewBottomInset = requiredInitialScrollViewBottomInset()
  107. }
  108. // MARK: - Initializers
  109. deinit {
  110. removeKeyboardObservers()
  111. removeMenuControllerObservers()
  112. removeObservers()
  113. clearMemoryCache()
  114. }
  115. // MARK: - Methods [Private]
  116. private func setupDefaults() {
  117. extendedLayoutIncludesOpaqueBars = true
  118. if #available(iOS 11.0, *) {} else {
  119. automaticallyAdjustsScrollViewInsets = false
  120. }
  121. view.backgroundColor = .white
  122. messagesCollectionView.keyboardDismissMode = .interactive
  123. messagesCollectionView.alwaysBounceVertical = true
  124. }
  125. private func setupDelegates() {
  126. messagesCollectionView.delegate = self
  127. messagesCollectionView.dataSource = self
  128. }
  129. private func setupSubviews() {
  130. view.addSubview(messagesCollectionView)
  131. }
  132. private func setupConstraints() {
  133. messagesCollectionView.translatesAutoresizingMaskIntoConstraints = false
  134. let top = messagesCollectionView.topAnchor.constraint(equalTo: view.topAnchor, constant: topLayoutGuide.length)
  135. let bottom = messagesCollectionView.bottomAnchor.constraint(equalTo: view.bottomAnchor)
  136. if #available(iOS 11.0, *) {
  137. let leading = messagesCollectionView.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor)
  138. let trailing = messagesCollectionView.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor)
  139. NSLayoutConstraint.activate([top, bottom, trailing, leading])
  140. } else {
  141. let leading = messagesCollectionView.leadingAnchor.constraint(equalTo: view.leadingAnchor)
  142. let trailing = messagesCollectionView.trailingAnchor.constraint(equalTo: view.trailingAnchor)
  143. NSLayoutConstraint.activate([top, bottom, trailing, leading])
  144. }
  145. }
  146. // MARK: - Typing Indicator API
  147. /// Sets the typing indicator sate by inserting/deleting the `TypingBubbleCell`
  148. ///
  149. /// - Parameters:
  150. /// - isHidden: A Boolean value that is to be the new state of the typing indicator
  151. /// - animated: A Boolean value determining if the insertion is to be animated
  152. /// - updates: A block of code that will be executed during `performBatchUpdates`
  153. /// when `animated` is `TRUE` or before the `completion` block executes
  154. /// when `animated` is `FALSE`
  155. /// - completion: A completion block to execute after the insertion/deletion
  156. open func setTypingIndicatorViewHidden(_ isHidden: Bool, animated: Bool, whilePerforming updates: (() -> Void)? = nil, completion: ((Bool) -> Void)? = nil) {
  157. guard isTypingIndicatorHidden != isHidden else {
  158. completion?(false)
  159. return
  160. }
  161. let section = messagesCollectionView.numberOfSections
  162. messagesCollectionView.setTypingIndicatorViewHidden(isHidden)
  163. if animated {
  164. messagesCollectionView.performBatchUpdates({ [weak self] in
  165. self?.performUpdatesForTypingIndicatorVisability(at: section)
  166. updates?()
  167. }, completion: completion)
  168. } else {
  169. performUpdatesForTypingIndicatorVisability(at: section)
  170. updates?()
  171. completion?(true)
  172. }
  173. }
  174. /// Performs a delete or insert on the `MessagesCollectionView` on the provided section
  175. ///
  176. /// - Parameter section: The index to modify
  177. private func performUpdatesForTypingIndicatorVisability(at section: Int) {
  178. if isTypingIndicatorHidden {
  179. messagesCollectionView.deleteSections([section - 1])
  180. } else {
  181. messagesCollectionView.insertSections([section])
  182. }
  183. }
  184. /// A method that by default checks if the section is the last in the
  185. /// `messagesCollectionView` and that `isTypingIndicatorViewHidden`
  186. /// is FALSE
  187. ///
  188. /// - Parameter section
  189. /// - Returns: A Boolean indicating if the TypingIndicator should be presented at the given section
  190. public func isSectionReservedForTypingIndicator(_ section: Int) -> Bool {
  191. return !messagesCollectionView.isTypingIndicatorHidden && section == self.numberOfSections(in: messagesCollectionView) - 1
  192. }
  193. // MARK: - UICollectionViewDataSource
  194. open func numberOfSections(in collectionView: UICollectionView) -> Int {
  195. guard let collectionView = collectionView as? MessagesCollectionView else {
  196. fatalError(MessageKitError.notMessagesCollectionView)
  197. }
  198. let sections = collectionView.messagesDataSource?.numberOfSections(in: collectionView) ?? 0
  199. return collectionView.isTypingIndicatorHidden ? sections : sections + 1
  200. }
  201. open func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
  202. guard let collectionView = collectionView as? MessagesCollectionView else {
  203. fatalError(MessageKitError.notMessagesCollectionView)
  204. }
  205. if isSectionReservedForTypingIndicator(section) {
  206. return 1
  207. }
  208. return collectionView.messagesDataSource?.numberOfItems(inSection: section, in: collectionView) ?? 0
  209. }
  210. /// Notes:
  211. /// - If you override this method, remember to call MessagesDataSource's customCell(for:at:in:)
  212. /// for MessageKind.custom messages, if necessary.
  213. ///
  214. /// - If you are using the typing indicator you will need to ensure that the section is not
  215. /// reserved for it with `isSectionReservedForTypingIndicator` defined in
  216. /// `MessagesCollectionViewFlowLayout`
  217. open func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
  218. guard let messagesCollectionView = collectionView as? MessagesCollectionView else {
  219. fatalError(MessageKitError.notMessagesCollectionView)
  220. }
  221. guard let messagesDataSource = messagesCollectionView.messagesDataSource else {
  222. fatalError(MessageKitError.nilMessagesDataSource)
  223. }
  224. if isSectionReservedForTypingIndicator(indexPath.section) {
  225. return messagesDataSource.typingIndicator(at: indexPath, in: messagesCollectionView)
  226. }
  227. let message = messagesDataSource.messageForItem(at: indexPath, in: messagesCollectionView)
  228. switch message.kind {
  229. case .text, .attributedText, .emoji:
  230. let cell = messagesCollectionView.dequeueReusableCell(TextMessageCell.self, for: indexPath)
  231. cell.configure(with: message, at: indexPath, and: messagesCollectionView)
  232. return cell
  233. case .info:
  234. let cell = messagesCollectionView.dequeueReusableCell(InfoMessageCell.self, for: indexPath)
  235. cell.configure(with: message, at: indexPath, and: messagesCollectionView)
  236. return cell
  237. case .photo, .video:
  238. let cell = messagesCollectionView.dequeueReusableCell(MediaMessageCell.self, for: indexPath)
  239. cell.configure(with: message, at: indexPath, and: messagesCollectionView)
  240. return cell
  241. case .photoText, .videoText, .fileText:
  242. let cell = messagesCollectionView.dequeueReusableCell(TextMediaMessageCell.self, for: indexPath)
  243. cell.configure(with: message, at: indexPath, and: messagesCollectionView)
  244. return cell
  245. case .location:
  246. let cell = messagesCollectionView.dequeueReusableCell(LocationMessageCell.self, for: indexPath)
  247. cell.configure(with: message, at: indexPath, and: messagesCollectionView)
  248. return cell
  249. case .audio:
  250. let cell = messagesCollectionView.dequeueReusableCell(AudioMessageCell.self, for: indexPath)
  251. cell.configure(with: message, at: indexPath, and: messagesCollectionView)
  252. return cell
  253. case .contact:
  254. let cell = messagesCollectionView.dequeueReusableCell(ContactMessageCell.self, for: indexPath)
  255. cell.configure(with: message, at: indexPath, and: messagesCollectionView)
  256. return cell
  257. case .custom:
  258. return messagesDataSource.customCell(for: message, at: indexPath, in: messagesCollectionView)
  259. }
  260. }
  261. open func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
  262. guard let messagesCollectionView = collectionView as? MessagesCollectionView else {
  263. fatalError(MessageKitError.notMessagesCollectionView)
  264. }
  265. guard let displayDelegate = messagesCollectionView.messagesDisplayDelegate else {
  266. fatalError(MessageKitError.nilMessagesDisplayDelegate)
  267. }
  268. switch kind {
  269. case UICollectionView.elementKindSectionHeader:
  270. return displayDelegate.messageHeaderView(for: indexPath, in: messagesCollectionView)
  271. case UICollectionView.elementKindSectionFooter:
  272. return displayDelegate.messageFooterView(for: indexPath, in: messagesCollectionView)
  273. default:
  274. fatalError(MessageKitError.unrecognizedSectionKind)
  275. }
  276. }
  277. // MARK: - UICollectionViewDelegateFlowLayout
  278. open func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
  279. guard let messagesFlowLayout = collectionViewLayout as? MessagesCollectionViewFlowLayout else { return .zero }
  280. return messagesFlowLayout.sizeForItem(at: indexPath)
  281. }
  282. open func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
  283. guard let messagesCollectionView = collectionView as? MessagesCollectionView else {
  284. fatalError(MessageKitError.notMessagesCollectionView)
  285. }
  286. guard let layoutDelegate = messagesCollectionView.messagesLayoutDelegate else {
  287. fatalError(MessageKitError.nilMessagesLayoutDelegate)
  288. }
  289. if isSectionReservedForTypingIndicator(section) {
  290. return .zero
  291. }
  292. return layoutDelegate.headerViewSize(for: section, in: messagesCollectionView)
  293. }
  294. open func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
  295. guard let cell = cell as? TypingIndicatorCell else { return }
  296. cell.typingBubble.startAnimating()
  297. }
  298. open func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
  299. guard let messagesCollectionView = collectionView as? MessagesCollectionView else {
  300. fatalError(MessageKitError.notMessagesCollectionView)
  301. }
  302. guard let layoutDelegate = messagesCollectionView.messagesLayoutDelegate else {
  303. fatalError(MessageKitError.nilMessagesLayoutDelegate)
  304. }
  305. if isSectionReservedForTypingIndicator(section) {
  306. return .zero
  307. }
  308. return layoutDelegate.footerViewSize(for: section, in: messagesCollectionView)
  309. }
  310. open func collectionView(_ collectionView: UICollectionView, shouldShowMenuForItemAt indexPath: IndexPath) -> Bool {
  311. guard let messagesDataSource = messagesCollectionView.messagesDataSource else { return false }
  312. if isSectionReservedForTypingIndicator(indexPath.section) {
  313. return false
  314. }
  315. let message = messagesDataSource.messageForItem(at: indexPath, in: messagesCollectionView)
  316. switch message.kind {
  317. case .text, .attributedText, .emoji, .photo, .photoText, .videoText, .fileText, .audio, .video:
  318. selectedIndexPathForMenu = indexPath
  319. return true
  320. default:
  321. return false
  322. }
  323. }
  324. open func collectionView(_ collectionView: UICollectionView, canPerformAction action: Selector, forItemAt indexPath: IndexPath, withSender sender: Any?) -> Bool {
  325. if isSectionReservedForTypingIndicator(indexPath.section) {
  326. return false
  327. }
  328. guard let messagesDataSource = messagesCollectionView.messagesDataSource else {
  329. fatalError(MessageKitError.nilMessagesDataSource)
  330. }
  331. let message = messagesDataSource.messageForItem(at: indexPath, in: messagesCollectionView)
  332. switch message.kind {
  333. case .text, .emoji, .attributedText, .fileText, .photoText, .videoText:
  334. return (action == NSSelectorFromString("copy:"))
  335. default:
  336. return false
  337. }
  338. }
  339. open func collectionView(_ collectionView: UICollectionView, performAction action: Selector, forItemAt indexPath: IndexPath, withSender sender: Any?) {
  340. guard let messagesDataSource = messagesCollectionView.messagesDataSource else {
  341. fatalError(MessageKitError.nilMessagesDataSource)
  342. }
  343. let pasteBoard = UIPasteboard.general
  344. let message = messagesDataSource.messageForItem(at: indexPath, in: messagesCollectionView)
  345. switch message.kind {
  346. case .text(let text), .emoji(let text):
  347. pasteBoard.string = text
  348. case .attributedText(let attributedText):
  349. pasteBoard.string = attributedText.string
  350. case .photoText(let mediaItem), .videoText(let mediaItem):
  351. pasteBoard.string = mediaItem.text?.string
  352. case .fileText(let mediaItem):
  353. pasteBoard.string = mediaItem.text?.string
  354. default:
  355. break
  356. }
  357. }
  358. // MARK: - Helpers
  359. private func addObservers() {
  360. NotificationCenter.default.addObserver(
  361. self, selector: #selector(clearMemoryCache), name: UIApplication.didReceiveMemoryWarningNotification, object: nil)
  362. }
  363. private func removeObservers() {
  364. NotificationCenter.default.removeObserver(self, name: UIApplication.didReceiveMemoryWarningNotification, object: nil)
  365. }
  366. @objc private func clearMemoryCache() {
  367. MessageStyle.bubbleImageCache.removeAllObjects()
  368. }
  369. }