Advertisement
Guest User

Untitled

a guest
Jun 25th, 2018
216
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Swift 10.53 KB | None | 0 0
  1. import UIKit
  2. import MessageKit
  3. import AVFoundation
  4.  
  5. let senders: [Sender] = [Sender(id: "283476", displayName: "Bogdan Bystritskiy"),
  6.                          Sender(id: "34556", displayName: "Valeria Ryabinicheva")
  7.                         ]
  8.  
  9. var messages: [MockMessage] = [
  10.                                MockMessage(sender: senders[0], messageId: senders[0].id, date: Date()-1505284,
  11.                                            text: "Dealing With Technical Support 10 Useful Tips"),
  12.                                MockMessage(sender: senders[1], messageId: senders[1].id, date: Date()-360364,
  13.                                            text: "Are You Ready To Buy A Home Theater Audio System"),
  14.                                MockMessage(sender: senders[0], messageId: senders[0].id, date: Date()-3600,
  15.                                            text: "Motivation And Your Personal Vision An Unbeatable Force"),
  16.                                MockMessage(sender: senders[1], messageId: senders[1].id, date: Date(), emoji: "😜"),
  17.                                MockMessage(sender: senders[0], messageId: senders[0].id, date: Date()-3600,
  18.                                            text: "Are You Ready To Buy A Home Theater Audio System"),
  19.                                MockMessage(sender: senders[0], messageId: senders[0].id, date: Date()-3600,
  20.                                            text: "Motivation And Your Personal Vision An Unbeatable Force"),
  21.                                MockMessage(sender: senders[1], messageId: senders[1].id, date: Date()-3600,
  22.                                            text: "Are You Ready To Buy A Home Theater Audio System"),
  23.                                MockMessage(sender: senders[0], messageId: senders[0].id, date: Date()-3600,
  24.                                            text: "Dealing With Technical Support 10 Useful Tips"),
  25.                                MockMessage(sender: senders[0], messageId: senders[0].id, date: Date()-3600,
  26.                                            text: "Motivation And Your Personal Vision An Unbeatable Force"),
  27.                                MockMessage(sender: senders[1], messageId: senders[1].id, date: Date(), emoji: "🤯")
  28.                                ]
  29.  
  30. class ChatDetailViewController: MessagesViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
  31.     var imagePicker = UIImagePickerController()
  32.    
  33.     lazy var formatter: DateFormatter = {
  34.         let formatter = DateFormatter()
  35.         formatter.dateStyle = .medium
  36.         return formatter
  37.     }()
  38.    
  39.     override func viewDidLoad() {
  40.         super.viewDidLoad()
  41.         configureNavigationBar()
  42.         configureMessageView()
  43.         hideKeyboardWhenTappedAround()
  44. //        imagePicker.delegate = self
  45.         DispatchQueue.main.async {
  46.             self.messagesCollectionView.reloadData()
  47.             self.messagesCollectionView.scrollToBottom()
  48.         }
  49.     }
  50.    
  51.     func hideKeyboardWhenTappedAround() {
  52.         let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(dismissKeyboard))
  53.         tapGestureRecognizer.cancelsTouchesInView = false
  54.         messagesCollectionView.addGestureRecognizer(tapGestureRecognizer)
  55.     }
  56.  
  57.     @objc func dismissKeyboard() {
  58.         messageInputBar.inputTextView.resignFirstResponder()
  59.     }
  60.    
  61.     func configureMessageView() {
  62.         messagesCollectionView.messagesDataSource = self
  63.         messagesCollectionView.messagesLayoutDelegate = self
  64.         messagesCollectionView.messagesDisplayDelegate = self
  65.         messageInputBar.delegate = self
  66.         messagesCollectionView.backgroundColor = .twPaleGray
  67.         maintainPositionOnKeyboardFrameChanged = true
  68.         scrollsToBottomOnKeybordBeginsEditing = true
  69.        
  70.         messageInputBar.inputTextView.placeholder = "Напишите сообщение..."
  71.         messageInputBar.sendButton.configure { (button) in
  72.             button.image = UIImage(named: "sendButton")
  73.             button.title = nil
  74.         }
  75.    
  76.         let leftButton = InputBarButtonItem()
  77.         leftButton.setImage(UIImage(named: "clip"), for: .normal)
  78.         leftButton.addTarget(self, action: #selector(addMedia), for: .allTouchEvents)
  79.         messageInputBar.setStackViewItems([leftButton], forStack: .left, animated: false)
  80.         leftButton.snp.makeConstraints { (make) in
  81.             make.centerY.equalTo(messageInputBar.sendButton.snp.centerY)
  82.         }
  83.         messageInputBar.setLeftStackViewWidthConstant(to: leftButton.intrinsicContentSize.width + 15, animated: false)
  84.        
  85.         if let img = UIImage(named: "oval") {
  86.             messages.append(MockMessage(sender: currentSender(), messageId: currentSender().id, date: Date(), photo: img))
  87.         }
  88.     }
  89.    
  90.     @objc func addMedia() {
  91.         if UIImagePickerController.isSourceTypeAvailable(.photoLibrary) {
  92.             print("Button capture")
  93.            
  94.             imagePicker.delegate = self
  95.             imagePicker.sourceType = .photoLibrary
  96.             imagePicker.allowsEditing = false
  97.            
  98.             self.present(imagePicker, animated: true, completion: nil)
  99.         }
  100.     }
  101.    
  102.     func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String: Any]) {
  103.         if let image = info[UIImagePickerControllerLivePhoto] as? UIImage {
  104.             messages.append(MockMessage(sender: currentSender(), messageId: currentSender().id, date: Date(), photo: image))
  105.             picker.dismiss(animated: true, completion: nil)
  106.         }
  107. //        picker.dismiss(animated: true, completion: nil)
  108.     }
  109.    
  110.     func configureNavigationBar() {
  111.         if #available(iOS 11.0, *) {
  112.             navigationController?.navigationBar.prefersLargeTitles = false
  113.         }
  114.         navigationController?.navigationBar.barTintColor = .twBlue
  115.         navigationController?.navigationBar.tintColor = .white
  116.         navigationItem.title = "Островский"
  117.         if let chatImage = UIImage(named: "oval") {
  118.             navigationItem.rightBarButtonItem = UIBarButtonItem(image: chatImage, style: .plain, target: self, action: nil)
  119.         }
  120.     }
  121. }
  122.  
  123. extension ChatDetailViewController: MessagesDataSource {
  124.     func numberOfMessages(in messagesCollectionView: MessagesCollectionView) -> Int {
  125.         return messages.count
  126.     }
  127.  
  128.     func currentSender() -> Sender {
  129.         return Sender(id: "34556", displayName: "Valeria Ryabinicheva")
  130.     }
  131.    
  132.     func numberOfSections(in messagesCollectionView: MessagesCollectionView) -> Int {
  133.         return messages.count
  134.     }
  135.    
  136.     func messageForItem(at indexPath: IndexPath, in messagesCollectionView: MessagesCollectionView) -> MessageType {
  137.         return messages[indexPath.section]
  138.     }
  139.    
  140.     func cellTopLabelAttributedText(for message: MessageType, at indexPath: IndexPath) -> NSAttributedString? {
  141.         let string = message.sender.displayName
  142.         if message.sender != currentSender() {
  143.             return NSAttributedString(string: string, attributes: [NSAttributedStringKey.foregroundColor: UIColor.twBlue,
  144.                                                                    NSAttributedStringKey.font: UIFont.systemFont(ofSize: 12)])
  145.         }
  146.         return nil
  147.     }
  148.    
  149.     func cellBottomLabelAttributedText(for message: MessageType, at indexPath: IndexPath) -> NSAttributedString? {
  150.         let date = formatter.string(from: message.sentDate)
  151.         return NSAttributedString(string: date, attributes: [NSAttributedStringKey.font: UIFont.systemFont(ofSize: 10),
  152.                                                              NSAttributedStringKey.foregroundColor: UIColor.twLightGray])
  153.     }
  154. }
  155.  
  156. extension ChatDetailViewController: MessagesLayoutDelegate {
  157.     func heightForLocation(message: MessageType, at indexPath: IndexPath, with maxWidth: CGFloat, in messagesCollectionView: MessagesCollectionView) -> CGFloat {
  158.         return 100
  159.     }
  160.     func cellBottomLabelAlignment(for message: MessageType, at indexPath: IndexPath, in messagesCollectionView: MessagesCollectionView) -> LabelAlignment {
  161.         return .messageTrailing(.zero)
  162.     }
  163.     func widthForMedia(message: MessageType, at indexPath: IndexPath, with maxWidth: CGFloat, in messagesCollectionView: MessagesCollectionView) -> CGFloat {
  164.         return (view.frame.width / 3) * 2
  165.     }
  166.     func heightForMedia(message: MessageType, at indexPath: IndexPath, with maxWidth: CGFloat, in messagesCollectionView: MessagesCollectionView) -> CGFloat {
  167.         return (view.frame.width / 3) * 2
  168.     }
  169. }
  170.  
  171. extension ChatDetailViewController: MessagesDisplayDelegate {
  172.     func configureAvatarView(_ avatarView: AvatarView, for message: MessageType, at indexPath: IndexPath, in messagesCollectionView: MessagesCollectionView) {
  173.         if let firstCharacter = message.sender.displayName.first {
  174.             let initials = String(firstCharacter)
  175.             avatarView.initials = initials
  176.         }
  177.     }
  178.     func backgroundColor(for message: MessageType, at  indexPath: IndexPath, in messagesCollectionView: MessagesCollectionView) -> UIColor {
  179.         switch message.data {
  180.         case .emoji:
  181.             return .clear
  182.         case .photo:
  183.             return .clear
  184.         default:
  185.             guard let dataSource = messagesCollectionView.messagesDataSource else { return .white }
  186.             return dataSource.isFromCurrentSender(message: message) ? UIColor.twBlue : UIColor.white
  187.         }
  188.     }
  189. }
  190.  
  191. extension ChatDetailViewController: MessageInputBarDelegate {
  192.  
  193.     func messageInputBar(_ inputBar: MessageInputBar, didPressSendButtonWith text: String) {
  194.         for component in inputBar.inputTextView.components {
  195.  
  196.             if let image = component as? UIImage {
  197.                 let imageMessage = MockMessage(sender: currentSender(), messageId: currentSender().id, date: Date(), photo: image)
  198.                 messages.append(imageMessage)
  199.                 messagesCollectionView.insertSections([messages.count - 1])
  200.  
  201.             } else if let text = component as? String {
  202.  
  203.                 let attributedText = NSAttributedString(string: text, attributes: [.font: UIFont.systemFont(ofSize: 15), .foregroundColor: UIColor.blue])
  204.  
  205.                 let message = MockMessage(sender: currentSender(), messageId: currentSender().id, date: Date(), attributedText: attributedText)
  206.                 messages.append(message)
  207.                 messagesCollectionView.insertSections([messages.count - 1])
  208.             }
  209.  
  210.         }
  211.         inputBar.inputTextView.text = String()
  212.         messagesCollectionView.scrollToBottom()
  213.     }
  214. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement