MessagesViewController.swift 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  1. /*
  2. MIT License
  3. Copyright (c) 2017-2018 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. /// A subclass of `UIViewController` with a `MessagesCollectionView` object
  22. /// that is used to display conversation interfaces.
  23. open class MessagesViewController: UIViewController,
  24. UICollectionViewDelegateFlowLayout, UICollectionViewDataSource {
  25. /// The `MessagesCollectionView` managed by the messages view controller object.
  26. open var messagesCollectionView = MessagesCollectionView()
  27. /// The `MessageInputBar` used as the `inputAccessoryView` in the view controller.
  28. open var messageInputBar = MessageInputBar()
  29. /// A Boolean value that determines whether the `MessagesCollectionView` scrolls to the
  30. /// bottom whenever the `InputTextView` begins editing.
  31. ///
  32. /// The default value of this property is `false`.
  33. open var scrollsToBottomOnKeybordBeginsEditing: Bool = false
  34. /// A Boolean value that determines whether the `MessagesCollectionView`
  35. /// maintains it's current position when the height of the `MessageInputBar` changes.
  36. ///
  37. /// The default value of this property is `false`.
  38. open var maintainPositionOnKeyboardFrameChanged: Bool = false
  39. open override var canBecomeFirstResponder: Bool {
  40. return true
  41. }
  42. open override var inputAccessoryView: UIView? {
  43. return messageInputBar
  44. }
  45. open override var shouldAutorotate: Bool {
  46. return false
  47. }
  48. private var isFirstLayout: Bool = true
  49. internal var isMessagesControllerBeingDismissed: Bool = false
  50. internal var selectedIndexPathForMenu: IndexPath?
  51. internal var messageCollectionViewBottomInset: CGFloat = 0 {
  52. didSet {
  53. messagesCollectionView.contentInset.bottom = messageCollectionViewBottomInset
  54. messagesCollectionView.scrollIndicatorInsets.bottom = messageCollectionViewBottomInset
  55. }
  56. }
  57. // MARK: - View Life Cycle
  58. open override func viewDidLoad() {
  59. super.viewDidLoad()
  60. setupDefaults()
  61. setupSubviews()
  62. setupConstraints()
  63. setupDelegates()
  64. addMenuControllerObservers()
  65. addObservers()
  66. }
  67. open override func viewDidAppear(_ animated: Bool) {
  68. super.viewDidAppear(animated)
  69. isMessagesControllerBeingDismissed = false
  70. }
  71. open override func viewWillDisappear(_ animated: Bool) {
  72. super.viewWillDisappear(animated)
  73. isMessagesControllerBeingDismissed = true
  74. }
  75. open override func viewDidLayoutSubviews() {
  76. // Hack to prevent animation of the contentInset after viewDidAppear
  77. if isFirstLayout {
  78. defer { isFirstLayout = false }
  79. addKeyboardObservers()
  80. messageCollectionViewBottomInset = keyboardOffsetFrame.height
  81. }
  82. adjustScrollViewInset()
  83. }
  84. // MARK: - Initializers
  85. deinit {
  86. removeKeyboardObservers()
  87. removeMenuControllerObservers()
  88. removeObservers()
  89. clearMemoryCache()
  90. }
  91. // MARK: - Methods [Private]
  92. private func setupDefaults() {
  93. extendedLayoutIncludesOpaqueBars = true
  94. automaticallyAdjustsScrollViewInsets = false
  95. view.backgroundColor = .white
  96. messagesCollectionView.keyboardDismissMode = .interactive
  97. messagesCollectionView.alwaysBounceVertical = true
  98. }
  99. private func setupDelegates() {
  100. messagesCollectionView.delegate = self
  101. messagesCollectionView.dataSource = self
  102. }
  103. private func setupSubviews() {
  104. view.addSubview(messagesCollectionView)
  105. }
  106. private func setupConstraints() {
  107. messagesCollectionView.translatesAutoresizingMaskIntoConstraints = false
  108. let top = messagesCollectionView.topAnchor.constraint(equalTo: view.topAnchor, constant: topLayoutGuide.length)
  109. let bottom = messagesCollectionView.bottomAnchor.constraint(equalTo: view.bottomAnchor)
  110. if #available(iOS 11.0, *) {
  111. let leading = messagesCollectionView.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor)
  112. let trailing = messagesCollectionView.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor)
  113. NSLayoutConstraint.activate([top, bottom, trailing, leading])
  114. } else {
  115. let leading = messagesCollectionView.leadingAnchor.constraint(equalTo: view.leadingAnchor)
  116. let trailing = messagesCollectionView.trailingAnchor.constraint(equalTo: view.trailingAnchor)
  117. NSLayoutConstraint.activate([top, bottom, trailing, leading])
  118. }
  119. }
  120. // MARK: - UICollectionViewDataSource
  121. open func numberOfSections(in collectionView: UICollectionView) -> Int {
  122. guard let collectionView = collectionView as? MessagesCollectionView else {
  123. fatalError(MessageKitError.notMessagesCollectionView)
  124. }
  125. return collectionView.messagesDataSource?.numberOfSections(in: collectionView) ?? 0
  126. }
  127. open func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
  128. guard let collectionView = collectionView as? MessagesCollectionView else {
  129. fatalError(MessageKitError.notMessagesCollectionView)
  130. }
  131. return collectionView.messagesDataSource?.numberOfItems(inSection: section, in: collectionView) ?? 0
  132. }
  133. open func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
  134. guard let messagesCollectionView = collectionView as? MessagesCollectionView else {
  135. fatalError(MessageKitError.notMessagesCollectionView)
  136. }
  137. guard let messagesDataSource = messagesCollectionView.messagesDataSource else {
  138. fatalError(MessageKitError.nilMessagesDataSource)
  139. }
  140. let message = messagesDataSource.messageForItem(at: indexPath, in: messagesCollectionView)
  141. switch message.kind {
  142. case .text, .attributedText, .emoji:
  143. let cell = messagesCollectionView.dequeueReusableCell(TextMessageCell.self, for: indexPath)
  144. cell.configure(with: message, at: indexPath, and: messagesCollectionView)
  145. return cell
  146. case .photo, .video:
  147. let cell = messagesCollectionView.dequeueReusableCell(MediaMessageCell.self, for: indexPath)
  148. cell.configure(with: message, at: indexPath, and: messagesCollectionView)
  149. return cell
  150. case .location:
  151. let cell = messagesCollectionView.dequeueReusableCell(LocationMessageCell.self, for: indexPath)
  152. cell.configure(with: message, at: indexPath, and: messagesCollectionView)
  153. return cell
  154. case .custom:
  155. fatalError(MessageKitError.customDataUnresolvedCell)
  156. }
  157. }
  158. open func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
  159. guard let messagesCollectionView = collectionView as? MessagesCollectionView else {
  160. fatalError(MessageKitError.notMessagesCollectionView)
  161. }
  162. guard let displayDelegate = messagesCollectionView.messagesDisplayDelegate else {
  163. fatalError(MessageKitError.nilMessagesDisplayDelegate)
  164. }
  165. switch kind {
  166. case UICollectionView.elementKindSectionHeader:
  167. return displayDelegate.messageHeaderView(for: indexPath, in: messagesCollectionView)
  168. case UICollectionView.elementKindSectionFooter:
  169. return displayDelegate.messageFooterView(for: indexPath, in: messagesCollectionView)
  170. default:
  171. fatalError(MessageKitError.unrecognizedSectionKind)
  172. }
  173. }
  174. // MARK: - UICollectionViewDelegateFlowLayout
  175. open func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
  176. guard let messagesFlowLayout = collectionViewLayout as? MessagesCollectionViewFlowLayout else { return .zero }
  177. return messagesFlowLayout.sizeForItem(at: indexPath)
  178. }
  179. open func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
  180. guard let messagesCollectionView = collectionView as? MessagesCollectionView else {
  181. fatalError(MessageKitError.notMessagesCollectionView)
  182. }
  183. guard let layoutDelegate = messagesCollectionView.messagesLayoutDelegate else {
  184. fatalError(MessageKitError.nilMessagesLayoutDelegate)
  185. }
  186. return layoutDelegate.headerViewSize(for: section, in: messagesCollectionView)
  187. }
  188. open func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
  189. guard let messagesCollectionView = collectionView as? MessagesCollectionView else {
  190. fatalError(MessageKitError.notMessagesCollectionView)
  191. }
  192. guard let layoutDelegate = messagesCollectionView.messagesLayoutDelegate else {
  193. fatalError(MessageKitError.nilMessagesLayoutDelegate)
  194. }
  195. return layoutDelegate.footerViewSize(for: section, in: messagesCollectionView)
  196. }
  197. open func collectionView(_ collectionView: UICollectionView, shouldShowMenuForItemAt indexPath: IndexPath) -> Bool {
  198. guard let messagesDataSource = messagesCollectionView.messagesDataSource else { return false }
  199. let message = messagesDataSource.messageForItem(at: indexPath, in: messagesCollectionView)
  200. switch message.kind {
  201. case .text, .attributedText, .emoji, .photo:
  202. selectedIndexPathForMenu = indexPath
  203. return true
  204. default:
  205. return false
  206. }
  207. }
  208. open func collectionView(_ collectionView: UICollectionView, canPerformAction action: Selector, forItemAt indexPath: IndexPath, withSender sender: Any?) -> Bool {
  209. return (action == NSSelectorFromString("copy:"))
  210. }
  211. open func collectionView(_ collectionView: UICollectionView, performAction action: Selector, forItemAt indexPath: IndexPath, withSender sender: Any?) {
  212. guard let messagesDataSource = messagesCollectionView.messagesDataSource else {
  213. fatalError(MessageKitError.nilMessagesDataSource)
  214. }
  215. let pasteBoard = UIPasteboard.general
  216. let message = messagesDataSource.messageForItem(at: indexPath, in: messagesCollectionView)
  217. switch message.kind {
  218. case .text(let text), .emoji(let text):
  219. pasteBoard.string = text
  220. case .attributedText(let attributedText):
  221. pasteBoard.string = attributedText.string
  222. case .photo(let mediaItem):
  223. pasteBoard.image = mediaItem.image ?? mediaItem.placeholderImage
  224. default:
  225. break
  226. }
  227. }
  228. // MARK: - Helpers
  229. private func addObservers() {
  230. NotificationCenter.default.addObserver(
  231. self, selector: #selector(clearMemoryCache), name: UIApplication.didReceiveMemoryWarningNotification, object: nil)
  232. }
  233. private func removeObservers() {
  234. NotificationCenter.default.removeObserver(self, name: UIApplication.didReceiveMemoryWarningNotification, object: nil)
  235. }
  236. @objc private func clearMemoryCache() {
  237. MessageStyle.bubbleImageCache.removeAllObjects()
  238. }
  239. }