Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //
- // ChatViewController.swift
- // Pure Rally
- //
- // Created by Mohamed Farouk Chedly on 2017-10-22.
- // Copyright © 2017 Mohamed Farouk Chedly. All rights reserved.
- //
- import UIKit
- import JSQMessagesViewController
- import MobileCoreServices
- import AVKit
- import FirebaseDatabase
- import FirebaseStorage
- import FirebaseAuth
- class ChatViewController: JSQMessagesViewController {
- var messages = [JSQMessage]()
- var messagesRef = DatabaseReference()
- var storageRef = StorageReference()
- override func viewDidLoad() {
- super.viewDidLoad()
- let currentUser = Auth.auth().currentUser
- self.senderId = currentUser?.uid
- self.senderDisplayName = "User"
- /*messagesRef.observeSingleEvent(of: .value, with: { (snapshot) in
- print(snapshot)
- })*/
- messagesRef = Database.database().reference().child("messages")
- storageRef = Storage.storage().reference().child("images")
- observeMessages()
- // Do any additional setup after loading the view.
- }
- func sendMedia(picture: UIImage?, video: NSURL?) {
- if let picture = picture {
- print(picture)
- print("*****")
- let filePath = "\(Auth.auth().currentUser!.uid)/\(NSDate.timeIntervalSinceReferenceDate)"
- let data = UIImageJPEGRepresentation(picture, 1)
- let metaData = StorageMetadata()
- metaData.contentType = "image/jpeg"
- storageRef.child(filePath).putData(data!, metadata: metaData) { (metaData,error ) in
- if error != nil {
- print("ettrrror")
- print(error?.localizedDescription)
- return
- }
- let fileUrl = metaData!.downloadURLs![0].absoluteString
- let newMessage = self.messagesRef.childByAutoId()
- let messageData = ["fileUrl": fileUrl, "senderId": self.senderId, "senderDisplayName": self.senderDisplayName, "mediaType": "PHOTO"]
- newMessage.setValue(messageData)
- }
- print("*****")
- } else if let video = video {
- let filePath = "\(Auth.auth().currentUser!.uid)/\(NSDate.timeIntervalSinceReferenceDate)"
- let data = NSData(contentsOf: video as URL)
- let metaData = StorageMetadata()
- metaData.contentType = "video/mp4"
- storageRef.child(filePath).putData(data! as Data, metadata: metaData) { (metaData,error ) in
- if error != nil {
- print("ettrrror")
- print(error?.localizedDescription)
- return
- }
- let fileUrl = metaData!.downloadURLs![0].absoluteString
- let newMessage = self.messagesRef.childByAutoId()
- let messageData = ["fileUrl": fileUrl, "senderId": self.senderId, "senderDisplayName": self.senderDisplayName, "mediaType": "VIDEO"]
- newMessage.setValue(messageData)
- }
- }
- }
- func observeMessages(){
- messagesRef.observe(DataEventType.childAdded) { (snapshot) in
- if let dict = snapshot.value as? [String: AnyObject] {
- let mediaType = dict["mediaType"] as! String
- let senderId = dict["senderId"] as! String
- let senderDisplayName = dict["senderDisplayName"] as! String
- if mediaType == "TEXT" {
- let text = dict["text"] as! String
- self.messages.append(JSQMessage(senderId: senderId, displayName: senderDisplayName, text: text))
- } else if mediaType == "PHOTO" {
- print("founde photo")
- let fileUrl = dict["fileUrl"] as! String
- print(fileUrl)
- let data = NSData(contentsOf: URL(string: fileUrl)!)
- print(data)
- let image = UIImage(data: data as! Data)
- let photo = JSQPhotoMediaItem(image: image)
- if self.senderId == senderId {
- photo?.appliesMediaViewMaskAsOutgoing = true
- } else {
- photo?.appliesMediaViewMaskAsOutgoing = false
- }
- self.messages.append(JSQMessage(senderId: self.senderId, displayName: self.senderDisplayName, media: photo))
- print("self.senderID")
- print(self.senderId)
- print("senderID")
- print(senderId)
- } else if mediaType == "VIDEO" {
- let fileUrlString = dict["fileUrl"] as! String
- let fileUrl = NSURL(string: fileUrlString)
- let videoItem = JSQVideoMediaItem(fileURL: fileUrl as! URL, isReadyToPlay: true)
- if self.senderId == senderId {
- videoItem?.appliesMediaViewMaskAsOutgoing = true
- } else {
- videoItem?.appliesMediaViewMaskAsOutgoing = false
- }
- self.messages.append(JSQMessage(senderId: self.senderId, displayName: self.senderDisplayName, media: videoItem))
- }
- self.collectionView.reloadData()
- }
- }
- }
- override func didPressSend(_ button: UIButton!, withMessageText text: String!, senderId: String!, senderDisplayName: String!, date: Date!) {
- print("didPressSend")
- print(text)
- /*
- messages.append(JSQMessage(senderId: senderId!, displayName: senderDisplayName, text: text))
- collectionView.reloadData()
- print(messages)*/
- let newMessage = messagesRef.childByAutoId()
- let messageData = ["text": text, "senderId": senderId, "senderDisplayName": senderDisplayName, "mediaType": "TEXT"]
- newMessage.setValue(messageData)
- self.finishSendingMessage()
- //self.scrollToBottom(animated: true) not working
- //let indexPath = IndexPath(row: , section: 0)
- //self.scroll(to: indexPath, animated: true)
- /*
- if self.collectionView.contentSize.height > self.collectionView.frame.height {
- self.collectionView.setContentOffset(
- CGPoint(x: 0, y: self.collectionView.contentSize.height
- - self.collectionView.frame.height + self.inputToolbar.bounds.height),
- animated: true)
- }*/
- }
- override func didPressAccessoryButton(_ sender: UIButton!) {
- print("didPressAccessoryButton")
- let sheet = UIAlertController(title: "Media Messages", message: "Please select a media", preferredStyle: UIAlertControllerStyle.actionSheet)
- let cancel = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.cancel) { (alert:UIAlertAction) in
- }
- let photoLibrary = UIAlertAction(title: "Photo Library", style: UIAlertActionStyle.default) { (alert: UIAlertAction) in
- self.getMediaFrom(type: kUTTypeImage)
- }
- let videoLibrary = UIAlertAction(title: "Video Library", style: UIAlertActionStyle.default) { (alert: UIAlertAction) in
- self.getMediaFrom(type: kUTTypeMovie)
- }
- sheet.addAction(photoLibrary)
- sheet.addAction(videoLibrary)
- sheet.addAction(cancel)
- self.present(sheet, animated: true, completion: nil)
- // let imagePicker = UIImagePickerController()
- // imagePicker.delegate = self
- // self.present(imagePicker, animated: true, completion: nil)
- }
- func getMediaFrom(type: CFString){
- let mediaPicker = UIImagePickerController()
- mediaPicker.delegate = self
- mediaPicker.mediaTypes = [type as String]
- self.present(mediaPicker, animated: true, completion: nil)
- }
- override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
- return messages.count
- }
- override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
- let cell = super.collectionView(collectionView, cellForItemAt: indexPath) as! JSQMessagesCollectionViewCell
- return cell
- }
- override func collectionView(_ collectionView: JSQMessagesCollectionView!, avatarImageDataForItemAt indexPath: IndexPath!) -> JSQMessageAvatarImageDataSource! {
- return nil
- }
- override func collectionView(_ collectionView: JSQMessagesCollectionView!, messageDataForItemAt indexPath: IndexPath!) -> JSQMessageData! {
- return messages[indexPath.item]
- }
- override func collectionView(_ collectionView: JSQMessagesCollectionView!, messageBubbleImageDataForItemAt indexPath: IndexPath!) -> JSQMessageBubbleImageDataSource! {
- let message = messages[indexPath.item]
- let bubbleFactory = JSQMessagesBubbleImageFactory()
- print("aaaaazzeazeazeazeazeazeazeaz");
- if message.senderId == self.senderId {
- return bubbleFactory?.outgoingMessagesBubbleImage(with: UIColor.black)
- } else {
- return bubbleFactory?.incomingMessagesBubbleImage(with: UIColor.purple)
- }
- }
- override func collectionView(_ collectionView: JSQMessagesCollectionView!, didTapMessageBubbleAt indexPath: IndexPath!) {
- print("didTapMessageBubbleAt \(indexPath.item)")
- let message = messages[indexPath.item]
- if message.isMediaMessage {
- if let mediaItem = message.media as? JSQVideoMediaItem {
- let player = AVPlayer(url: mediaItem.fileURL)
- let playerViewController = AVPlayerViewController()
- playerViewController.player = player
- self.present(playerViewController, animated: true, completion: nil)
- }
- }
- }
- override func didReceiveMemoryWarning() {
- super.didReceiveMemoryWarning()
- // Dispose of any resources that can be recreated.
- }
- /*
- // MARK: - Navigation
- // In a storyboard-based application, you will often want to do a little preparation before navigation
- override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
- // Get the new view controller using segue.destinationViewController.
- // Pass the selected object to the new view controller.
- }
- */
- }
- extension ChatViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
- func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
- print("Did finish picking media file")
- print(info)
- if let picture = info[UIImagePickerControllerOriginalImage] as? UIImage {
- let photo = JSQPhotoMediaItem(image: picture)
- messages.append(JSQMessage(senderId: senderId, senderDisplayName: senderDisplayName, date: Date(), media: photo))
- sendMedia(picture: picture, video: nil)
- } else if let video = info[UIImagePickerControllerMediaURL] as? NSURL {
- let videoMedia = JSQVideoMediaItem(fileURL: video as URL!, isReadyToPlay: true)
- messages.append(JSQMessage(senderId: senderId, senderDisplayName: senderDisplayName, date: Date(), media: videoMedia))
- sendMedia(picture: nil, video: video)
- }
- self.dismiss(animated: true, completion: nil)
- collectionView.reloadData()
- }
- }
- #####
- ###Login
- ####
- //
- // LogInViewController.swift
- // Pure Rally
- //
- // Created by Mohamed Farouk Chedly on 2017-10-22.
- // Copyright © 2017 Mohamed Farouk Chedly. All rights reserved.
- //
- import UIKit
- import FirebaseAuth
- import SVProgressHUD
- class LogInViewController: UIViewController {
- @IBOutlet weak var emailTextField: UITextField!
- @IBOutlet weak var passwordTextField: UITextField!
- @IBOutlet weak var logInButtton: UIButton!
- override func viewDidLoad() {
- super.viewDidLoad()
- logInButtton.isEnabled = false
- handleTextFields()
- // Do any additional setup after loading the view.
- }
- override func viewDidAppear(_ animated: Bool) {
- super.viewDidAppear(animated)
- // refactor add loading auth adn redirecting
- Auth.auth().addStateDidChangeListener { (auth, user) in
- if user != nil {
- print("already auth \(auth)")
- // redirect user to home (main chat + future feature maps)
- // Create a main stroyboard instance
- let storyboard = UIStoryboard(name: "Main", bundle: nil)
- // From main storyboard instaniate a navigation controller
- let navigationVC = storyboard.instantiateViewController(withIdentifier: "NavigationVC") as! UINavigationController
- // Get the app delegate
- let appDelegate = UIApplication.shared.delegate as! AppDelegate
- // Set navigation controller as root view controller
- appDelegate.window?.rootViewController = navigationVC
- } else {
- print("not auth")
- }
- }
- }
- override func didReceiveMemoryWarning() {
- super.didReceiveMemoryWarning()
- // Dispose of any resources that can be recreated.
- }
- @IBAction func logInDidTapped(_ sender: Any) {
- print("Log In tapped")
- // TODO: Check email && password fields
- //
- SVProgressHUD.show(withStatus: "Loading...")
- // Firebase auth
- Auth.auth().signIn(withEmail: emailTextField.text!, password: passwordTextField.text!) { (user, error) in
- if (error != nil) {
- // Error
- print(error!.localizedDescription)
- return
- }
- // Sign in successfully
- print("User Id: \(user!.uid)")
- // Create a main stroyboard instance
- let storyboard = UIStoryboard(name: "Main", bundle: nil)
- // From main storyboard instaniate a navigation controller
- let navigationVC = storyboard.instantiateViewController(withIdentifier: "NavigationVC") as! UINavigationController
- // Get the app delegate
- let appDelegate = UIApplication.shared.delegate as! AppDelegate
- // Set navigation controller as root view controller
- appDelegate.window?.rootViewController = navigationVC
- }
- }
- func handleTextFields() {
- emailTextField.addTarget(self, action: #selector(LogInViewController.textFieldsDidChange), for: UIControlEvents.editingChanged)
- passwordTextField.addTarget(self, action: #selector(LogInViewController.textFieldsDidChange), for: UIControlEvents.editingChanged)
- }
- @objc func textFieldsDidChange() {
- guard let email = emailTextField.text, !email.isEmpty, let password = passwordTextField.text, !password.isEmpty else {
- logInButtton.setTitleColor(UIColor.red, for: UIControlState.normal)
- logInButtton.isEnabled = false
- return
- }
- logInButtton.setTitleColor(UIColor.blue, for: UIControlState.normal)
- logInButtton.isEnabled = true
- }
- /*
- // MARK: - Navigation
- // In a storyboard-based application, you will often want to do a little preparation before navigation
- override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
- // Get the new view controller using segue.destinationViewController.
- // Pass the selected object to the new view controller.
- }
- */
- }
- #####
- ####Home#
- ####
- //
- // HomeViewController.swift
- // Pure Rally
- //
- // Created by Mohamed Farouk Chedly on 2017-10-22.
- // Copyright © 2017 Mohamed Farouk Chedly. All rights reserved.
- //
- import UIKit
- import FirebaseAuth
- class HomeViewController: UIViewController {
- override func viewDidLoad() {
- super.viewDidLoad()
- // Do any additional setup after loading the view.
- }
- override func didReceiveMemoryWarning() {
- super.didReceiveMemoryWarning()
- // Dispose of any resources that can be recreated.
- }
- @IBAction func logOutTapped(_ sender: Any) {
- print("Log Out tapped")
- let firebaseAuth = Auth.auth()
- do {
- try firebaseAuth.signOut()
- } catch let signOutError as NSError {
- print ("Error signing out: %@", signOutError)
- }
- // Create a main stroyboard instance
- let storyboard = UIStoryboard(name: "Main", bundle: nil)
- // From main storyboard instaniate a tab bar controller
- let mainTabBarController = storyboard.instantiateViewController(withIdentifier: "MainTabBarController") as! UITabBarController
- // Get the app delegate
- let appDelegate = UIApplication.shared.delegate as! AppDelegate
- // Set navigation controller as root view controller
- appDelegate.window?.rootViewController = mainTabBarController
- }
- /*
- // MARK: - Navigation
- // In a storyboard-based application, you will often want to do a little preparation before navigation
- override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
- // Get the new view controller using segue.destinationViewController.
- // Pass the selected object to the new view controller.
- }
- */
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement