Guest User

Untitled

a guest
Nov 23rd, 2017
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 3.09 KB | None | 0 0
  1. import UIKit
  2. import Firebase
  3.  
  4. class NotesTableViewController: UITableViewController, SaveNoteDelegate {
  5.  
  6. var ref: DatabaseReference!
  7.  
  8. var notes = [Notes]()
  9. var currentUserName = "Here comes the username"
  10.  
  11.  
  12. override func viewDidLoad() {
  13. super.viewDidLoad()
  14. title = currentUserName
  15.  
  16. }
  17.  
  18. override func numberOfSections(in tableView: UITableView) -> Int {
  19.  
  20. return 1
  21. }
  22.  
  23. override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
  24. return notes.count
  25. }
  26.  
  27.  
  28. override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
  29. let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! NotesTableViewCell
  30.  
  31. cell.userNameLabel.text = notes[indexPath.row].name
  32. cell.userImage.image = notes[indexPath.row].userImage
  33. return cell
  34. }
  35.  
  36. override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
  37. if segue.identifier == "notesToWrite", let destination = segue.destination as? WriteViewController {
  38. destination.delegate = self
  39. }
  40. }
  41.  
  42. override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
  43. return 250
  44. }
  45.  
  46.  
  47. func saveNote(note: Notes) {
  48. notes.append(note)
  49. let storageRef = Storage.storage().reference()
  50. let imagesRef = storageRef.child("PushImageAttachment")
  51. let fileName = "pushImage.jpg"
  52. let spaceRef = imagesRef.child(fileName)
  53. if let data = UIImageJPEGRepresentation(note.userImage, 0.6) {
  54.  
  55. spaceRef.putData(data, metadata: nil, completion: { [unowned self] (metadata, error) in
  56. if error != nil {
  57. print(error?.localizedDescription)
  58. return
  59. }
  60. if let imgURL = metadata?.downloadURL()?.absoluteString {
  61. self.handleNoteSave(note: note, imageURL: imgURL)
  62. }
  63. })
  64. }
  65.  
  66. }
  67.  
  68. func handleNoteSave(note: Notes, imageURL: String) {
  69. ref = Database.database().reference()
  70. let noteToSave = ["name" : currentUserName, "message": note.name, "imageURL": imageURL] as [String: Any]
  71.  
  72. ref.child("users").child(currentUserName).setValue(noteToSave) { (error, dataRef) in
  73. if error != nil {
  74. print("error occured", error?.localizedDescription ?? "")
  75. } else {
  76. DispatchQueue.main.async {
  77. self.tableView.reloadData()
  78. }
  79. print("success")
  80. }
  81. }
  82. }
  83.  
  84. }
Add Comment
Please, Sign In to add comment