MessagesViewController.swift 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419
  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. automaticallyAdjustsScrollViewInsets = false
  119. view.backgroundColor = .white
  120. messagesCollectionView.keyboardDismissMode = .interactive
  121. messagesCollectionView.alwaysBounceVertical = true
  122. }
  123. private func setupDelegates() {
  124. messagesCollectionView.delegate = self
  125. messagesCollectionView.dataSource = self
  126. }
  127. private func setupSubviews() {
  128. view.addSubview(messagesCollectionView)
  129. }
  130. private func setupConstraints() {
  131. messagesCollectionView.translatesAutoresizingMaskIntoConstraints = false
  132. let top = messagesCollectionView.topAnchor.constraint(equalTo: view.topAnchor, constant: topLayoutGuide.length)
  133. let bottom = messagesCollectionView.bottomAnchor.constraint(equalTo: view.bottomAnchor)
  134. if #available(iOS 11.0, *) {
  135. let leading = messagesCollectionView.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor)
  136. let trailing = messagesCollectionView.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor)
  137. NSLayoutConstraint.activate([top, bottom, trailing, leading])
  138. } else {
  139. let leading = messagesCollectionView.leadingAnchor.constraint(equalTo: view.leadingAnchor)
  140. let trailing = messagesCollectionView.trailingAnchor.constraint(equalTo: view.trailingAnchor)
  141. NSLayoutConstraint.activate([top, bottom, trailing, leading])
  142. }
  143. }
  144. // MARK: - Typing Indicator API
  145. /// Sets the typing indicator sate by inserting/deleting the `TypingBubbleCell`
  146. ///
  147. /// - Parameters:
  148. /// - isHidden: A Boolean value that is to be the new state of the typing indicator
  149. /// - animated: A Boolean value determining if the insertion is to be animated
  150. /// - updates: A block of code that will be executed during `performBatchUpdates`
  151. /// when `animated` is `TRUE` or before the `completion` block executes
  152. /// when `animated` is `FALSE`
  153. /// - completion: A completion block to execute after the insertion/deletion
  154. open func setTypingIndicatorViewHidden(_ isHidden: Bool, animated: Bool, whilePerforming updates: (() -> Void)? = nil, completion: ((Bool) -> Void)? = nil) {
  155. guard isTypingIndicatorHidden != isHidden else {
  156. completion?(false)
  157. return
  158. }
  159. let section = messagesCollectionView.numberOfSections
  160. messagesCollectionView.setTypingIndicatorViewHidden(isHidden)
  161. if animated {
  162. messagesCollectionView.performBatchUpdates({ [weak self] in
  163. self?.performUpdatesForTypingIndicatorVisability(at: section)
  164. updates?()
  165. }, completion: completion)
  166. } else {
  167. performUpdatesForTypingIndicatorVisability(at: section)
  168. updates?()
  169. completion?(true)
  170. }
  171. }
  172. /// Performs a delete or insert on the `MessagesCollectionView` on the provided section
  173. ///
  174. /// - Parameter section: The index to modify
  175. private func performUpdatesForTypingIndicatorVisability(at section: Int) {
  176. if isTypingIndicatorHidden {
  177. messagesCollectionView.deleteSections([section - 1])
  178. } else {
  179. messagesCollectionView.insertSections([section])
  180. }
  181. }
  182. /// A method that by default checks if the section is the last in the
  183. /// `messagesCollectionView` and that `isTypingIndicatorViewHidden`
  184. /// is FALSE
  185. ///
  186. /// - Parameter section
  187. /// - Returns: A Boolean indicating if the TypingIndicator should be presented at the given section
  188. public func isSectionReservedForTypingIndicator(_ section: Int) -> Bool {
  189. return !messagesCollectionView.isTypingIndicatorHidden && section == self.numberOfSections(in: messagesCollectionView) - 1
  190. }
  191. // MARK: - UICollectionViewDataSource
  192. open func numberOfSections(in collectionView: UICollectionView) -> Int {
  193. guard let collectionView = collectionView as? MessagesCollectionView else {
  194. fatalError(MessageKitError.notMessagesCollectionView)
  195. }
  196. let sections = collectionView.messagesDataSource?.numberOfSections(in: collectionView) ?? 0
  197. return collectionView.isTypingIndicatorHidden ? sections : sections + 1
  198. }
  199. open func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
  200. guard let collectionView = collectionView as? MessagesCollectionView else {
  201. fatalError(MessageKitError.notMessagesCollectionView)
  202. }
  203. if isSectionReservedForTypingIndicator(section) {
  204. return 1
  205. }
  206. return collectionView.messagesDataSource?.numberOfItems(inSection: section, in: collectionView) ?? 0
  207. }
  208. /// Notes:
  209. /// - If you override this method, remember to call MessagesDataSource's customCell(for:at:in:)
  210. /// for MessageKind.custom messages, if necessary.
  211. ///
  212. /// - If you are using the typing indicator you will need to ensure that the section is not
  213. /// reserved for it with `isSectionReservedForTypingIndicator` defined in
  214. /// `MessagesCollectionViewFlowLayout`
  215. open func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
  216. guard let messagesCollectionView = collectionView as? MessagesCollectionView else {
  217. fatalError(MessageKitError.notMessagesCollectionView)
  218. }
  219. guard let messagesDataSource = messagesCollectionView.messagesDataSource else {
  220. fatalError(MessageKitError.nilMessagesDataSource)
  221. }
  222. if isSectionReservedForTypingIndicator(indexPath.section) {
  223. return messagesDataSource.typingIndicator(at: indexPath, in: messagesCollectionView)
  224. }
  225. let message = messagesDataSource.messageForItem(at: indexPath, in: messagesCollectionView)
  226. switch message.kind {
  227. case .text, .attributedText, .emoji:
  228. let cell = messagesCollectionView.dequeueReusableCell(TextMessageCell.self, for: indexPath)
  229. cell.configure(with: message, at: indexPath, and: messagesCollectionView)
  230. return cell
  231. case .photo, .video:
  232. let cell = messagesCollectionView.dequeueReusableCell(MediaMessageCell.self, for: indexPath)
  233. cell.configure(with: message, at: indexPath, and: messagesCollectionView)
  234. return cell
  235. case .location:
  236. let cell = messagesCollectionView.dequeueReusableCell(LocationMessageCell.self, for: indexPath)
  237. cell.configure(with: message, at: indexPath, and: messagesCollectionView)
  238. return cell
  239. case .audio:
  240. let cell = messagesCollectionView.dequeueReusableCell(AudioMessageCell.self, for: indexPath)
  241. cell.configure(with: message, at: indexPath, and: messagesCollectionView)
  242. return cell
  243. case .contact:
  244. let cell = messagesCollectionView.dequeueReusableCell(ContactMessageCell.self, for: indexPath)
  245. cell.configure(with: message, at: indexPath, and: messagesCollectionView)
  246. return cell
  247. case .custom:
  248. return messagesDataSource.customCell(for: message, at: indexPath, in: messagesCollectionView)
  249. }
  250. }
  251. open func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
  252. guard let messagesCollectionView = collectionView as? MessagesCollectionView else {
  253. fatalError(MessageKitError.notMessagesCollectionView)
  254. }
  255. guard let displayDelegate = messagesCollectionView.messagesDisplayDelegate else {
  256. fatalError(MessageKitError.nilMessagesDisplayDelegate)
  257. }
  258. switch kind {
  259. case UICollectionView.elementKindSectionHeader:
  260. return displayDelegate.messageHeaderView(for: indexPath, in: messagesCollectionView)
  261. case UICollectionView.elementKindSectionFooter:
  262. return displayDelegate.messageFooterView(for: indexPath, in: messagesCollectionView)
  263. default:
  264. fatalError(MessageKitError.unrecognizedSectionKind)
  265. }
  266. }
  267. // MARK: - UICollectionViewDelegateFlowLayout
  268. open func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
  269. guard let messagesFlowLayout = collectionViewLayout as? MessagesCollectionViewFlowLayout else { return .zero }
  270. return messagesFlowLayout.sizeForItem(at: indexPath)
  271. }
  272. open func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
  273. guard let messagesCollectionView = collectionView as? MessagesCollectionView else {
  274. fatalError(MessageKitError.notMessagesCollectionView)
  275. }
  276. guard let layoutDelegate = messagesCollectionView.messagesLayoutDelegate else {
  277. fatalError(MessageKitError.nilMessagesLayoutDelegate)
  278. }
  279. if isSectionReservedForTypingIndicator(section) {
  280. return .zero
  281. }
  282. return layoutDelegate.headerViewSize(for: section, in: messagesCollectionView)
  283. }
  284. open func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
  285. guard let cell = cell as? TypingIndicatorCell else { return }
  286. cell.typingBubble.startAnimating()
  287. }
  288. open func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
  289. guard let messagesCollectionView = collectionView as? MessagesCollectionView else {
  290. fatalError(MessageKitError.notMessagesCollectionView)
  291. }
  292. guard let layoutDelegate = messagesCollectionView.messagesLayoutDelegate else {
  293. fatalError(MessageKitError.nilMessagesLayoutDelegate)
  294. }
  295. if isSectionReservedForTypingIndicator(section) {
  296. return .zero
  297. }
  298. return layoutDelegate.footerViewSize(for: section, in: messagesCollectionView)
  299. }
  300. open func collectionView(_ collectionView: UICollectionView, shouldShowMenuForItemAt indexPath: IndexPath) -> Bool {
  301. guard let messagesDataSource = messagesCollectionView.messagesDataSource else { return false }
  302. if isSectionReservedForTypingIndicator(indexPath.section) {
  303. return false
  304. }
  305. let message = messagesDataSource.messageForItem(at: indexPath, in: messagesCollectionView)
  306. switch message.kind {
  307. case .text, .attributedText, .emoji, .photo:
  308. selectedIndexPathForMenu = indexPath
  309. return true
  310. default:
  311. return false
  312. }
  313. }
  314. open func collectionView(_ collectionView: UICollectionView, canPerformAction action: Selector, forItemAt indexPath: IndexPath, withSender sender: Any?) -> Bool {
  315. if isSectionReservedForTypingIndicator(indexPath.section) {
  316. return false
  317. }
  318. return (action == NSSelectorFromString("copy:"))
  319. }
  320. open func collectionView(_ collectionView: UICollectionView, performAction action: Selector, forItemAt indexPath: IndexPath, withSender sender: Any?) {
  321. guard let messagesDataSource = messagesCollectionView.messagesDataSource else {
  322. fatalError(MessageKitError.nilMessagesDataSource)
  323. }
  324. let pasteBoard = UIPasteboard.general
  325. let message = messagesDataSource.messageForItem(at: indexPath, in: messagesCollectionView)
  326. switch message.kind {
  327. case .text(let text), .emoji(let text):
  328. pasteBoard.string = text
  329. case .attributedText(let attributedText):
  330. pasteBoard.string = attributedText.string
  331. case .photo(let mediaItem):
  332. pasteBoard.image = mediaItem.image ?? mediaItem.placeholderImage
  333. default:
  334. break
  335. }
  336. }
  337. // MARK: - Helpers
  338. private func addObservers() {
  339. NotificationCenter.default.addObserver(
  340. self, selector: #selector(clearMemoryCache), name: UIApplication.didReceiveMemoryWarningNotification, object: nil)
  341. }
  342. private func removeObservers() {
  343. NotificationCenter.default.removeObserver(self, name: UIApplication.didReceiveMemoryWarningNotification, object: nil)
  344. }
  345. @objc private func clearMemoryCache() {
  346. MessageStyle.bubbleImageCache.removeAllObjects()
  347. }
  348. }