Firebase + TableView: #上傳檔案

  • Chat room app

    •  ( tvcSimpleChatCell.swift)

    1. //
      // tvcSimpleChatCell.swift
      // TNFSHChat
      //
      // Created by yen yung chin on 2018/5/24.
      // Copyright © 2018 Letranger.tw. All rights reserved.
      //

      import UIKit
      import Kingfisher

      class tvcSimpleChatCell: UITableViewCell {

      @IBOutlet weak var lblContent: UILabel!
      @IBOutlet weak var lblUserDate: UILabel!

      @IBOutlet weak var imgPhoto: UIImageView!
      override func awakeFromNib() {
      super.awakeFromNib()
      }

      func setChat(chat:Chat) {
      lblContent.text = chat.content
      lblUserDate.text = "\(chat.userName!) @ \(chat.datePost!))"


      let imgUrl = URL(string: "\(chat.imgUrl!)")
      imgPhoto.kf.setImage(with: imgUrl)
      imgPhoto.contentMode = .scaleAspectFit
      }

      override func setSelected(_ selected: Bool, animated: Bool) {
      super.setSelected(selected, animated: animated)

      // Configure the view for the selected state
      }



      }

    2.  ( vcLoginView.swift )
      //
      // vcLoginView.swift
      // TNFSHChat
      //
      // Created by yen yung chin on 2018/5/24.
      // Copyright © 2018 Letranger.tw. All rights reserved.
      //

      import UIKit

      class vcLoginView: 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.
      }

      @IBOutlet weak var txtUserName: UITextField!

      @IBAction func btnLogin(_ sender: UIButton) {
      performSegue(withIdentifier: "chatRoom", sender: self)
      }
      /*
      // 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.
      }
      */
      override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
      if segue.identifier == "chatRoom" {
      if let distView = segue.destination as? ViewController {
      distView.chatUserName = txtUserName.text
      }
      }
      }
      }

    3. (chat.swift)
    4. //
      // Chat.swift
      // TNFSHChat
      //
      // Created by yen yung chin on 2018/5/24.
      // Copyright © 2018 Letranger.tw. All rights reserved.
      //

      import Foundation
      class Chat {
      var userName: String?
      var content: String?
      var imgUrl: String?
      var datePost: String?

      init(userName: String, content: String, imgUrl: String, datePost: String) {
      self.userName = userName
      self.content = content
      self.imgUrl = imgUrl
      self.datePost = datePost
      }
      }

    5. //
      // ViewController.swift
      // TNFSHChat
      //
      // Created by yen yung chin on 2018/5/23.
      // Copyright © 2018 Letranger.tw. All rights reserved.
      //

      import UIKit
      import Firebase
      import FirebaseStorage

      class ViewController: UIViewController,UINavigationControllerDelegate, UIImagePickerControllerDelegate, UITableViewDataSource, UITableViewDelegate{

      func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
      return listOfChatInfo.count
      }

      func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
      let cell:tvcSimpleChatCell = (tableView.dequeueReusableCell(withIdentifier: "cellChat", for: indexPath) as? tvcSimpleChatCell)!
      cell.setChat(chat: listOfChatInfo[indexPath.row])
      return cell
      }
      func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
      return 70
      }
      var chatUserName: String?
      var ref: DatabaseReference!
      var uploadImageUrl = String()
      @IBOutlet weak var imgPhoto: UIImageView!

      @IBAction func btnSend(_ sender: UIButton) {
      let uniqueString = NSUUID().uuidString
      print("*********\(uniqueString)")
      let storageRef = Storage.storage().reference().child("chat").child("\(uniqueString).png")
      if let uploadImg = UIImagePNGRepresentation(imgPhoto.image!) {
      storageRef.putData(uploadImg, metadata: nil) { (data, error) in
      if error != nil {
      print("upload image error: \(error!)")
      return
      }
      if let uploadImageUrl = data?.downloadURL()?.absoluteString {
      let chat = [ "content": self.txtChatContent.text as Any,
      "user": self.chatUserName as Any,
      "photo": "\(uploadImageUrl)",
      "postDate": ServerValue.timestamp()] as [String : Any]
      self.ref.child("chat").childByAutoId().setValue(chat)
      self.txtChatContent.text = ""
      }
      }
      }
      }
      @IBOutlet weak var tvChatList: UITableView!


      @IBOutlet weak var txtChatContent: UITextField!
      override func viewDidLoad() {
      super.viewDidLoad()

      tvChatList.delegate = self
      tvChatList.dataSource = self
      // Link to FireBase
      ref = Database.database().reference()
      loginAnony()
      self.hideKeyboardWhenTappedAround()
      }
      var listOfChatInfo = [Chat]()

      func loadChatRoom () {
      let chatPosts = ref.child("chat").queryOrdered(byChild: "postDate").observe(.value) {
      (snapshot) in
      //
      self.listOfChatInfo.removeAll()
      if let snapshot = snapshot.children.allObjects as? [DataSnapshot] {
      for snap in snapshot {
      if let post = snap.value as? [String : AnyObject] {
      let username = post["user"] as? String
      let text = post["content"] as? String
      let photoUrl = post["photo"] as? String
      let date = self.getStrDate(unixtimeInterval: post["postDate"] as! TimeInterval)
      self.listOfChatInfo.append(Chat(userName: username!, content: text!, imgUrl: photoUrl!, datePost: "\(date)"))
      }
      }
      self.tvChatList.reloadData()
      let indexpath = IndexPath(row: self.listOfChatInfo.count-1, section: 0)
      self.tvChatList.scrollToRow(at: indexpath, at: .bottom, animated: true)
      }
      }
      }

      func getStrDate(unixtimeInterval: TimeInterval) -> String {

      let date = NSDate(timeIntervalSince1970: unixtimeInterval/1000)
      let dateFormatter = DateFormatter()
      dateFormatter.timeZone = TimeZone.current
      dateFormatter.locale = NSLocale.current
      dateFormatter.dateFormat = "yyyy.MM.dd hh:mm"
      return dateFormatter.string(from: date as Date)
      }

      @IBAction func btnChangePhoto(_ sender: Any) {
      // 選圖片
      let image = UIImagePickerController()
      image.delegate = self
      image.sourceType = .photoLibrary
      // 把選圖片的view叫出來
      self.present(image, animated: true, completion: nil)
      }

      func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
      imgPhoto.image = (info["UIImagePickerControllerOriginalImage"] as! UIImage)
      self.dismiss(animated: true, completion: nil)
      }

      func loginAnony() {
      Auth.auth().signInAnonymously { (user, error) in
      if let error = error {
      print("Cannot login: \(error)")
      } else {
      print("user \(String(describing: user?.uid))")
      self.loadChatRoom()
      }
      }
      }

      }

      extension UIViewController {
      func hideKeyboardWhenTappedAround() {
      let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(UIViewController.dismissKeyboard))
      tap.cancelsTouchesInView = false
      view.addGestureRecognizer(tap)
      }
      @objc func dismissKeyboard() {
      view.endEditing(true)
      }
      }


Last modified: Friday, 21 June 2019, 9:51 AM