MessagesViewController.swift 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  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. import MessageInputBar
  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 `MessageInputBar` used as the `inputAccessoryView` in the view controller.
  29. open var messageInputBar = MessageInputBar()
  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. private var isFirstLayout: Bool = true
  60. internal var isMessagesControllerBeingDismissed: Bool = false
  61. internal var selectedIndexPathForMenu: IndexPath?
  62. internal var messageCollectionViewBottomInset: CGFloat = 0 {
  63. didSet {
  64. messagesCollectionView.contentInset.bottom = messageCollectionViewBottomInset
  65. messagesCollectionView.scrollIndicatorInsets.bottom = messageCollectionViewBottomInset
  66. }
  67. }
  68. // MARK: - View Life Cycle
  69. open override func viewDidLoad() {
  70. super.viewDidLoad()
  71. setupDefaults()
  72. setupSubviews()
  73. setupConstraints()
  74. setupDelegates()
  75. addMenuControllerObservers()
  76. addObservers()
  77. }
  78. open override func viewDidAppear(_ animated: Bool) {
  79. super.viewDidAppear(animated)
  80. isMessagesControllerBeingDismissed = false
  81. }
  82. open override func viewWillDisappear(_ animated: Bool) {
  83. super.viewWillDisappear(animated)
  84. isMessagesControllerBeingDismissed = true
  85. }
  86. open override func viewDidDisappear(_ animated: Bool) {
  87. super.viewDidDisappear(animated)
  88. isMessagesControllerBeingDismissed = false
  89. }
  90. open override func viewDidLayoutSubviews() {
  91. // Hack to prevent animation of the contentInset after viewDidAppear
  92. if isFirstLayout {
  93. defer { isFirstLayout = false }
  94. addKeyboardObservers()
  95. messageCollectionViewBottomInset = requiredInitialScrollViewBottomInset()
  96. }
  97. adjustScrollViewTopInset()
  98. }
  99. // MARK: - Initializers
  100. deinit {
  101. removeKeyboardObservers()
  102. removeMenuControllerObservers()
  103. removeObservers()
  104. clearMemoryCache()
  105. }
  106. // MARK: - Methods [Private]
  107. private func setupDefaults() {
  108. extendedLayoutIncludesOpaqueBars = true
  109. automaticallyAdjustsScrollViewInsets = false
  110. view.backgroundColor = .white
  111. messagesCollectionView.keyboardDismissMode = .interactive
  112. messagesCollectionView.alwaysBounceVertical = true
  113. }
  114. private func setupDelegates() {
  115. messagesCollectionView.delegate = self
  116. messagesCollectionView.dataSource = self
  117. }
  118. private func setupSubviews() {
  119. view.addSubview(messagesCollectionView)
  120. }
  121. private func setupConstraints() {
  122. messagesCollectionView.translatesAutoresizingMaskIntoConstraints = false
  123. let top = messagesCollectionView.topAnchor.constraint(equalTo: view.topAnchor, constant: topLayoutGuide.length)
  124. let bottom = messagesCollectionView.bottomAnchor.constraint(equalTo: view.bottomAnchor)
  125. if #available(iOS 11.0, *) {
  126. let leading = messagesCollectionView.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor)
  127. let trailing = messagesCollectionView.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor)
  128. NSLayoutConstraint.activate([top, bottom, trailing, leading])
  129. } else {
  130. let leading = messagesCollectionView.leadingAnchor.constraint(equalTo: view.leadingAnchor)
  131. let trailing = messagesCollectionView.trailingAnchor.constraint(equalTo: view.trailingAnchor)
  132. NSLayoutConstraint.activate([top, bottom, trailing, leading])
  133. }
  134. }
  135. // MARK: - UICollectionViewDataSource
  136. open func numberOfSections(in collectionView: UICollectionView) -> Int {
  137. guard let collectionView = collectionView as? MessagesCollectionView else {
  138. fatalError(MessageKitError.notMessagesCollectionView)
  139. }
  140. return collectionView.messagesDataSource?.numberOfSections(in: collectionView) ?? 0
  141. }
  142. open func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
  143. guard let collectionView = collectionView as? MessagesCollectionView else {
  144. fatalError(MessageKitError.notMessagesCollectionView)
  145. }
  146. return collectionView.messagesDataSource?.numberOfItems(inSection: section, in: collectionView) ?? 0
  147. }
  148. /// Note:
  149. /// If you override this method, remember to call MessagesDataSource's customCell(for:at:in:) for MessageKind.custom messages, if necessary
  150. open func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
  151. guard let messagesCollectionView = collectionView as? MessagesCollectionView else {
  152. fatalError(MessageKitError.notMessagesCollectionView)
  153. }
  154. guard let messagesDataSource = messagesCollectionView.messagesDataSource else {
  155. fatalError(MessageKitError.nilMessagesDataSource)
  156. }
  157. let message = messagesDataSource.messageForItem(at: indexPath, in: messagesCollectionView)
  158. switch message.kind {
  159. case .text, .attributedText, .emoji:
  160. let cell = messagesCollectionView.dequeueReusableCell(TextMessageCell.self, for: indexPath)
  161. cell.configure(with: message, at: indexPath, and: messagesCollectionView)
  162. return cell
  163. case .photo, .video:
  164. let cell = messagesCollectionView.dequeueReusableCell(MediaMessageCell.self, for: indexPath)
  165. cell.configure(with: message, at: indexPath, and: messagesCollectionView)
  166. return cell
  167. case .location:
  168. let cell = messagesCollectionView.dequeueReusableCell(LocationMessageCell.self, for: indexPath)
  169. cell.configure(with: message, at: indexPath, and: messagesCollectionView)
  170. return cell
  171. case .custom:
  172. return messagesDataSource.customCell(for: message, at: indexPath, in: messagesCollectionView)
  173. }
  174. }
  175. open func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
  176. guard let messagesCollectionView = collectionView as? MessagesCollectionView else {
  177. fatalError(MessageKitError.notMessagesCollectionView)
  178. }
  179. guard let displayDelegate = messagesCollectionView.messagesDisplayDelegate else {
  180. fatalError(MessageKitError.nilMessagesDisplayDelegate)
  181. }
  182. switch kind {
  183. case UICollectionView.elementKindSectionHeader:
  184. return displayDelegate.messageHeaderView(for: indexPath, in: messagesCollectionView)
  185. case UICollectionView.elementKindSectionFooter:
  186. return displayDelegate.messageFooterView(for: indexPath, in: messagesCollectionView)
  187. default:
  188. fatalError(MessageKitError.unrecognizedSectionKind)
  189. }
  190. }
  191. // MARK: - UICollectionViewDelegateFlowLayout
  192. open func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
  193. guard let messagesFlowLayout = collectionViewLayout as? MessagesCollectionViewFlowLayout else { return .zero }
  194. return messagesFlowLayout.sizeForItem(at: indexPath)
  195. }
  196. open func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
  197. guard let messagesCollectionView = collectionView as? MessagesCollectionView else {
  198. fatalError(MessageKitError.notMessagesCollectionView)
  199. }
  200. guard let layoutDelegate = messagesCollectionView.messagesLayoutDelegate else {
  201. fatalError(MessageKitError.nilMessagesLayoutDelegate)
  202. }
  203. return layoutDelegate.headerViewSize(for: section, in: messagesCollectionView)
  204. }
  205. open func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
  206. guard let messagesCollectionView = collectionView as? MessagesCollectionView else {
  207. fatalError(MessageKitError.notMessagesCollectionView)
  208. }
  209. guard let layoutDelegate = messagesCollectionView.messagesLayoutDelegate else {
  210. fatalError(MessageKitError.nilMessagesLayoutDelegate)
  211. }
  212. return layoutDelegate.footerViewSize(for: section, in: messagesCollectionView)
  213. }
  214. open func collectionView(_ collectionView: UICollectionView, shouldShowMenuForItemAt indexPath: IndexPath) -> Bool {
  215. guard let messagesDataSource = messagesCollectionView.messagesDataSource else { return false }
  216. let message = messagesDataSource.messageForItem(at: indexPath, in: messagesCollectionView)
  217. switch message.kind {
  218. case .text, .attributedText, .emoji, .photo:
  219. selectedIndexPathForMenu = indexPath
  220. return true
  221. default:
  222. return false
  223. }
  224. }
  225. open func collectionView(_ collectionView: UICollectionView, canPerformAction action: Selector, forItemAt indexPath: IndexPath, withSender sender: Any?) -> Bool {
  226. return (action == NSSelectorFromString("copy:"))
  227. }
  228. open func collectionView(_ collectionView: UICollectionView, performAction action: Selector, forItemAt indexPath: IndexPath, withSender sender: Any?) {
  229. guard let messagesDataSource = messagesCollectionView.messagesDataSource else {
  230. fatalError(MessageKitError.nilMessagesDataSource)
  231. }
  232. let pasteBoard = UIPasteboard.general
  233. let message = messagesDataSource.messageForItem(at: indexPath, in: messagesCollectionView)
  234. switch message.kind {
  235. case .text(let text), .emoji(let text):
  236. pasteBoard.string = text
  237. case .attributedText(let attributedText):
  238. pasteBoard.string = attributedText.string
  239. case .photo(let mediaItem):
  240. pasteBoard.image = mediaItem.image ?? mediaItem.placeholderImage
  241. default:
  242. break
  243. }
  244. }
  245. // MARK: - Helpers
  246. private func addObservers() {
  247. NotificationCenter.default.addObserver(
  248. self, selector: #selector(clearMemoryCache), name: UIApplication.didReceiveMemoryWarningNotification, object: nil)
  249. }
  250. private func removeObservers() {
  251. NotificationCenter.default.removeObserver(self, name: UIApplication.didReceiveMemoryWarningNotification, object: nil)
  252. }
  253. @objc private func clearMemoryCache() {
  254. MessageStyle.bubbleImageCache.removeAllObjects()
  255. }
  256. }