Advertisement
Guest User

Untitled

a guest
Oct 26th, 2017
151
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Swift 18.15 KB | None | 0 0
  1. //
  2. //  ChatViewController.swift
  3. //  Pure Rally
  4. //
  5. //  Created by Mohamed Farouk Chedly on 2017-10-22.
  6. //  Copyright © 2017 Mohamed Farouk Chedly. All rights reserved.
  7. //
  8.  
  9. import UIKit
  10. import JSQMessagesViewController
  11. import MobileCoreServices
  12. import AVKit
  13. import FirebaseDatabase
  14. import FirebaseStorage
  15. import FirebaseAuth
  16.  
  17. class ChatViewController: JSQMessagesViewController {
  18.    
  19.     var messages = [JSQMessage]()
  20.     var messagesRef = DatabaseReference()
  21.     var storageRef = StorageReference()
  22.    
  23.    
  24.  
  25.     override func viewDidLoad() {
  26.         super.viewDidLoad()
  27.         let currentUser = Auth.auth().currentUser
  28.        
  29.         self.senderId = currentUser?.uid
  30.         self.senderDisplayName = "User"
  31.        
  32.         /*messagesRef.observeSingleEvent(of: .value, with: { (snapshot) in
  33.            print(snapshot)
  34.         })*/
  35.        
  36.         messagesRef = Database.database().reference().child("messages")
  37.         storageRef = Storage.storage().reference().child("images")
  38.        
  39.         observeMessages()
  40.        
  41.         // Do any additional setup after loading the view.
  42.     }
  43.    
  44.     func sendMedia(picture: UIImage?, video: NSURL?) {
  45.         if let picture = picture {
  46.             print(picture)
  47.             print("*****")
  48.             let filePath = "\(Auth.auth().currentUser!.uid)/\(NSDate.timeIntervalSinceReferenceDate)"
  49.             let data = UIImageJPEGRepresentation(picture, 1)
  50.             let metaData = StorageMetadata()
  51.             metaData.contentType = "image/jpeg"
  52.            
  53.             storageRef.child(filePath).putData(data!, metadata: metaData) { (metaData,error ) in
  54.                 if error != nil {
  55.                     print("ettrrror")
  56.                     print(error?.localizedDescription)
  57.                     return
  58.                 }
  59.                 let fileUrl = metaData!.downloadURLs![0].absoluteString
  60.                
  61.                 let newMessage = self.messagesRef.childByAutoId()
  62.                 let messageData = ["fileUrl": fileUrl, "senderId": self.senderId, "senderDisplayName": self.senderDisplayName, "mediaType": "PHOTO"]
  63.                 newMessage.setValue(messageData)
  64.                
  65.                
  66.             }
  67.             print("*****")
  68.         } else if let video = video {
  69.             let filePath = "\(Auth.auth().currentUser!.uid)/\(NSDate.timeIntervalSinceReferenceDate)"
  70.             let data = NSData(contentsOf: video as URL)
  71.             let metaData = StorageMetadata()
  72.             metaData.contentType = "video/mp4"
  73.            
  74.             storageRef.child(filePath).putData(data! as Data, metadata: metaData) { (metaData,error ) in
  75.                 if error != nil {
  76.                     print("ettrrror")
  77.                     print(error?.localizedDescription)
  78.                     return
  79.                 }
  80.                 let fileUrl = metaData!.downloadURLs![0].absoluteString
  81.                
  82.                 let newMessage = self.messagesRef.childByAutoId()
  83.                 let messageData = ["fileUrl": fileUrl, "senderId": self.senderId, "senderDisplayName": self.senderDisplayName, "mediaType": "VIDEO"]
  84.                 newMessage.setValue(messageData)
  85.                
  86.                
  87.             }
  88.         }
  89.        
  90.    
  91.     }
  92.    
  93.     func observeMessages(){
  94.         messagesRef.observe(DataEventType.childAdded) { (snapshot) in
  95.             if let dict = snapshot.value as? [String: AnyObject] {
  96.                 let mediaType = dict["mediaType"] as! String
  97.                 let senderId = dict["senderId"] as! String
  98.                 let senderDisplayName = dict["senderDisplayName"] as! String
  99.                
  100.                 if mediaType == "TEXT" {
  101.                     let text = dict["text"] as! String
  102.                     self.messages.append(JSQMessage(senderId: senderId, displayName: senderDisplayName, text: text))
  103.                    
  104.                 } else if mediaType == "PHOTO" {
  105.                     print("founde photo")
  106.              
  107.                     let fileUrl = dict["fileUrl"] as! String
  108.                     print(fileUrl)
  109.                     let data = NSData(contentsOf: URL(string: fileUrl)!)
  110.                     print(data)
  111.                     let image = UIImage(data: data as! Data)
  112.                     let photo = JSQPhotoMediaItem(image: image)
  113.                    
  114.                     if self.senderId == senderId {
  115.                         photo?.appliesMediaViewMaskAsOutgoing = true
  116.                     } else {
  117.                         photo?.appliesMediaViewMaskAsOutgoing = false
  118.                        
  119.                     }
  120.                     self.messages.append(JSQMessage(senderId: self.senderId, displayName: self.senderDisplayName, media: photo))
  121.                     print("self.senderID")
  122.                     print(self.senderId)
  123.                     print("senderID")
  124.                     print(senderId)
  125.                
  126.                 } else if mediaType == "VIDEO" {
  127.                       let fileUrlString = dict["fileUrl"] as! String
  128.                     let fileUrl = NSURL(string: fileUrlString)
  129.                     let videoItem = JSQVideoMediaItem(fileURL: fileUrl as! URL, isReadyToPlay: true)
  130.                    
  131.                     if self.senderId == senderId {
  132.                        
  133.                         videoItem?.appliesMediaViewMaskAsOutgoing = true
  134.                     } else {
  135.                         videoItem?.appliesMediaViewMaskAsOutgoing = false
  136.                     }
  137.                    
  138.                       self.messages.append(JSQMessage(senderId: self.senderId, displayName: self.senderDisplayName, media: videoItem))
  139.                    
  140.                 }
  141.                
  142.         self.collectionView.reloadData()
  143.             }
  144.         }
  145.     }
  146.    
  147.     override func didPressSend(_ button: UIButton!, withMessageText text: String!, senderId: String!, senderDisplayName: String!, date: Date!) {
  148.        
  149.         print("didPressSend")
  150.         print(text)
  151.          /*
  152.         messages.append(JSQMessage(senderId: senderId!, displayName: senderDisplayName, text: text))
  153.         collectionView.reloadData()
  154.         print(messages)*/
  155.        
  156.         let newMessage = messagesRef.childByAutoId()
  157.         let messageData = ["text": text, "senderId": senderId, "senderDisplayName": senderDisplayName, "mediaType": "TEXT"]
  158.         newMessage.setValue(messageData)
  159.         self.finishSendingMessage()
  160.    
  161.         //self.scrollToBottom(animated: true) not working
  162.         //let indexPath = IndexPath(row: , section: 0)
  163.         //self.scroll(to: indexPath, animated: true)
  164.         /*
  165.         if self.collectionView.contentSize.height > self.collectionView.frame.height {
  166.             self.collectionView.setContentOffset(
  167.                 CGPoint(x: 0, y: self.collectionView.contentSize.height
  168.                     - self.collectionView.frame.height + self.inputToolbar.bounds.height),
  169.                 animated: true)
  170.         }*/
  171.        
  172.     }
  173.    
  174.  
  175.    
  176.     override func didPressAccessoryButton(_ sender: UIButton!) {
  177.         print("didPressAccessoryButton")
  178.         let sheet = UIAlertController(title: "Media Messages", message: "Please select a media", preferredStyle: UIAlertControllerStyle.actionSheet)
  179.        
  180.         let cancel = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.cancel) { (alert:UIAlertAction) in
  181.         }
  182.        
  183.         let photoLibrary = UIAlertAction(title: "Photo Library", style: UIAlertActionStyle.default) { (alert: UIAlertAction) in
  184.             self.getMediaFrom(type: kUTTypeImage)
  185.         }
  186.        
  187.         let videoLibrary = UIAlertAction(title: "Video Library", style: UIAlertActionStyle.default) { (alert: UIAlertAction) in
  188.             self.getMediaFrom(type: kUTTypeMovie)
  189.         }
  190.        
  191.         sheet.addAction(photoLibrary)
  192.         sheet.addAction(videoLibrary)
  193.         sheet.addAction(cancel)
  194.        
  195.         self.present(sheet, animated: true, completion: nil)
  196.        
  197.         // let imagePicker = UIImagePickerController()
  198.         // imagePicker.delegate = self
  199.         // self.present(imagePicker, animated: true, completion: nil)
  200.     }
  201.    
  202.    
  203.     func getMediaFrom(type: CFString){
  204.         let mediaPicker = UIImagePickerController()
  205.         mediaPicker.delegate = self
  206.         mediaPicker.mediaTypes = [type as String]
  207.         self.present(mediaPicker, animated: true, completion: nil)
  208.     }
  209.    
  210.     override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
  211.         return messages.count
  212.     }
  213.    
  214.     override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
  215.         let cell = super.collectionView(collectionView, cellForItemAt: indexPath) as! JSQMessagesCollectionViewCell
  216.         return cell
  217.     }
  218.    
  219.     override func collectionView(_ collectionView: JSQMessagesCollectionView!, avatarImageDataForItemAt indexPath: IndexPath!) -> JSQMessageAvatarImageDataSource! {
  220.         return nil
  221.     }
  222.     override func collectionView(_ collectionView: JSQMessagesCollectionView!, messageDataForItemAt indexPath: IndexPath!) -> JSQMessageData! {
  223.         return messages[indexPath.item]
  224.     }
  225.    
  226.     override func collectionView(_ collectionView: JSQMessagesCollectionView!, messageBubbleImageDataForItemAt indexPath: IndexPath!) -> JSQMessageBubbleImageDataSource! {
  227.         let message = messages[indexPath.item]
  228.         let bubbleFactory = JSQMessagesBubbleImageFactory()
  229.         print("aaaaazzeazeazeazeazeazeazeaz");
  230.        
  231.         if message.senderId == self.senderId {
  232.             return bubbleFactory?.outgoingMessagesBubbleImage(with: UIColor.black)
  233.         } else {
  234.            
  235.             return bubbleFactory?.incomingMessagesBubbleImage(with: UIColor.purple)
  236.         }
  237.        
  238.     }
  239.    
  240.     override func collectionView(_ collectionView: JSQMessagesCollectionView!, didTapMessageBubbleAt indexPath: IndexPath!) {
  241.         print("didTapMessageBubbleAt \(indexPath.item)")
  242.         let message = messages[indexPath.item]
  243.         if message.isMediaMessage {
  244.             if let mediaItem = message.media as? JSQVideoMediaItem {
  245.                 let player = AVPlayer(url: mediaItem.fileURL)
  246.                 let playerViewController = AVPlayerViewController()
  247.                 playerViewController.player = player
  248.                 self.present(playerViewController, animated: true, completion: nil)
  249.             }
  250.         }
  251.     }
  252.    
  253.     override func didReceiveMemoryWarning() {
  254.         super.didReceiveMemoryWarning()
  255.         // Dispose of any resources that can be recreated.
  256.     }
  257.    
  258.  
  259.     /*
  260.     // MARK: - Navigation
  261.  
  262.     // In a storyboard-based application, you will often want to do a little preparation before navigation
  263.     override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
  264.         // Get the new view controller using segue.destinationViewController.
  265.         // Pass the selected object to the new view controller.
  266.     }
  267.     */
  268.  
  269. }
  270.  
  271.  
  272. extension ChatViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
  273.     func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
  274.         print("Did finish picking media file")
  275.         print(info)
  276.         if let picture = info[UIImagePickerControllerOriginalImage] as? UIImage {
  277.             let photo = JSQPhotoMediaItem(image: picture)
  278.             messages.append(JSQMessage(senderId: senderId, senderDisplayName: senderDisplayName, date: Date(), media: photo))
  279.             sendMedia(picture: picture, video: nil)
  280.         } else if let video = info[UIImagePickerControllerMediaURL] as? NSURL {
  281.             let videoMedia = JSQVideoMediaItem(fileURL: video as URL!, isReadyToPlay: true)
  282.             messages.append(JSQMessage(senderId: senderId, senderDisplayName: senderDisplayName, date: Date(), media: videoMedia))
  283.             sendMedia(picture: nil, video: video)
  284.         }
  285.        
  286.         self.dismiss(animated: true, completion: nil)
  287.         collectionView.reloadData()
  288.        
  289.     }
  290. }
  291.  
  292.  
  293. #####
  294. ###Login
  295. ####
  296.  
  297. //
  298. //  LogInViewController.swift
  299. //  Pure Rally
  300. //
  301. //  Created by Mohamed Farouk Chedly on 2017-10-22.
  302. //  Copyright © 2017 Mohamed Farouk Chedly. All rights reserved.
  303. //
  304.  
  305. import UIKit
  306. import FirebaseAuth
  307. import SVProgressHUD
  308.  
  309. class LogInViewController: UIViewController {
  310.    
  311.     @IBOutlet weak var emailTextField: UITextField!
  312.     @IBOutlet weak var passwordTextField: UITextField!
  313.     @IBOutlet weak var logInButtton: UIButton!
  314.    
  315.     override func viewDidLoad() {
  316.         super.viewDidLoad()
  317.         logInButtton.isEnabled = false
  318.         handleTextFields()
  319.         // Do any additional setup after loading the view.
  320.     }
  321.    
  322.     override func viewDidAppear(_ animated: Bool) {
  323.         super.viewDidAppear(animated)
  324.         // refactor add loading auth adn redirecting
  325.         Auth.auth().addStateDidChangeListener { (auth, user) in
  326.             if user != nil {
  327.                 print("already auth \(auth)")
  328.                 // redirect user to home (main chat + future feature maps)
  329.                 // Create a main stroyboard instance
  330.                 let storyboard = UIStoryboard(name: "Main", bundle: nil)
  331.                
  332.                 // From main storyboard instaniate a navigation controller
  333.                 let navigationVC = storyboard.instantiateViewController(withIdentifier: "NavigationVC") as! UINavigationController
  334.                
  335.                 // Get the app delegate
  336.                 let appDelegate = UIApplication.shared.delegate as! AppDelegate
  337.                
  338.                 // Set navigation controller as root view controller
  339.                 appDelegate.window?.rootViewController = navigationVC
  340.             } else {
  341.                 print("not auth")
  342.             }
  343.         }
  344.     }
  345.  
  346.     override func didReceiveMemoryWarning() {
  347.         super.didReceiveMemoryWarning()
  348.         // Dispose of any resources that can be recreated.
  349.     }
  350.    
  351.     @IBAction func logInDidTapped(_ sender: Any) {
  352.         print("Log In tapped")
  353.        
  354.         // TODO: Check email && password fields
  355.        
  356.         //
  357.         SVProgressHUD.show(withStatus: "Loading...")
  358.         // Firebase auth
  359.        
  360.         Auth.auth().signIn(withEmail: emailTextField.text!, password: passwordTextField.text!) { (user, error) in
  361.             if (error != nil) {
  362.                 // Error
  363.                 print(error!.localizedDescription)
  364.                 return
  365.             }
  366.             // Sign in successfully
  367.             print("User Id: \(user!.uid)")
  368.            
  369.             // Create a main stroyboard instance
  370.             let storyboard = UIStoryboard(name: "Main", bundle: nil)
  371.            
  372.             // From main storyboard instaniate a navigation controller
  373.             let navigationVC = storyboard.instantiateViewController(withIdentifier: "NavigationVC") as! UINavigationController
  374.            
  375.             // Get the app delegate
  376.             let appDelegate = UIApplication.shared.delegate as! AppDelegate
  377.            
  378.             // Set navigation controller as root view controller
  379.             appDelegate.window?.rootViewController = navigationVC
  380.                
  381.            
  382.         }
  383.        
  384.     }
  385.    
  386.     func handleTextFields() {
  387.         emailTextField.addTarget(self, action: #selector(LogInViewController.textFieldsDidChange), for: UIControlEvents.editingChanged)
  388.         passwordTextField.addTarget(self, action: #selector(LogInViewController.textFieldsDidChange), for: UIControlEvents.editingChanged)
  389.     }
  390.    
  391.     @objc func textFieldsDidChange() {
  392.         guard let email = emailTextField.text, !email.isEmpty, let password = passwordTextField.text, !password.isEmpty else {
  393.             logInButtton.setTitleColor(UIColor.red, for: UIControlState.normal)
  394.             logInButtton.isEnabled = false
  395.             return
  396.         }
  397.         logInButtton.setTitleColor(UIColor.blue, for: UIControlState.normal)
  398.         logInButtton.isEnabled = true
  399.     }
  400.    
  401.     /*
  402.     // MARK: - Navigation
  403.  
  404.     // In a storyboard-based application, you will often want to do a little preparation before navigation
  405.     override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
  406.         // Get the new view controller using segue.destinationViewController.
  407.         // Pass the selected object to the new view controller.
  408.     }
  409.     */
  410.  
  411. }
  412.  
  413.  
  414. #####
  415. ####Home#
  416. ####
  417. //
  418. //  HomeViewController.swift
  419. //  Pure Rally
  420. //
  421. //  Created by Mohamed Farouk Chedly on 2017-10-22.
  422. //  Copyright © 2017 Mohamed Farouk Chedly. All rights reserved.
  423. //
  424.  
  425. import UIKit
  426. import FirebaseAuth
  427.  
  428. class HomeViewController: UIViewController {
  429.  
  430.     override func viewDidLoad() {
  431.         super.viewDidLoad()
  432.  
  433.         // Do any additional setup after loading the view.
  434.     }
  435.  
  436.     override func didReceiveMemoryWarning() {
  437.         super.didReceiveMemoryWarning()
  438.         // Dispose of any resources that can be recreated.
  439.     }
  440.    
  441.     @IBAction func logOutTapped(_ sender: Any) {
  442.         print("Log Out tapped")
  443.        
  444.        
  445.         let firebaseAuth = Auth.auth()
  446.         do {
  447.             try firebaseAuth.signOut()
  448.         } catch let signOutError as NSError {
  449.             print ("Error signing out: %@", signOutError)
  450.         }
  451.        
  452.         // Create a main stroyboard instance
  453.         let storyboard = UIStoryboard(name: "Main", bundle: nil)
  454.        
  455.         // From main storyboard instaniate a tab bar controller
  456.         let mainTabBarController = storyboard.instantiateViewController(withIdentifier: "MainTabBarController") as! UITabBarController
  457.        
  458.         // Get the app delegate
  459.         let appDelegate = UIApplication.shared.delegate as! AppDelegate
  460.        
  461.         // Set navigation controller as root view controller
  462.         appDelegate.window?.rootViewController = mainTabBarController
  463.     }
  464.    
  465.     /*
  466.     // MARK: - Navigation
  467.  
  468.     // In a storyboard-based application, you will often want to do a little preparation before navigation
  469.     override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
  470.         // Get the new view controller using segue.destinationViewController.
  471.         // Pass the selected object to the new view controller.
  472.     }
  473.     */
  474.  
  475. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement