Advertisement
Guest User

extension

a guest
Jul 24th, 2017
57
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 13.59 KB | None | 0 0
  1. //
  2. // FeedViewController.swift
  3. // Heply
  4. //
  5. // Created by marllons on 30/05/17.
  6. // Copyright © 2017 ifce. All rights reserved.
  7. //
  8.  
  9. import UIKit
  10. import FirebaseAuth
  11. import GooglePlaces
  12. import GooglePlacePicker
  13. import SCLAlertView
  14. import NVActivityIndicatorView
  15.  
  16. protocol CustomTextViewDelegate: class {
  17. func editingStatus(_ state: Bool)
  18. }
  19.  
  20. class FeedViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, SendDataBack, CreateCellDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate, UITabBarControllerDelegate {
  21.  
  22. //MARK: - Outlets
  23. @IBOutlet weak var tableView: UITableView!
  24. @IBOutlet weak var activityIndicator: NVActivityIndicatorView!
  25.  
  26. //MARK: - Actions
  27.  
  28.  
  29. //MARK: - Variables
  30. var selectedImage: UIImage?
  31. var posts = [Post]()
  32. let refreshControl = UIRefreshControl()
  33. let requisition = FirebaseRequisition()
  34. var createPostHeight = CGFloat(102)
  35. var dictionaryPost = [String: String]()
  36. let transition = CATransition()
  37. var isFirst: Bool?
  38. var tableViewGoToTop = true
  39. var createPostTextViewState: Bool = false
  40.  
  41. //MARK: - ViewDidLoad
  42. override func viewDidLoad() {
  43. super.viewDidLoad()
  44.  
  45. // appDelegate.handleLogout(self)
  46. SwipeView.desativateTimer()
  47.  
  48. //Requisiçao para salvar dados do usuário no singleton
  49. requisition.requisitonLogin((Auth.auth().currentUser?.uid)!){(newBool) -> (Void) in
  50. if !(newBool!){
  51. let appearance = SCLAlertView.SCLAppearance(
  52. showCloseButton: false
  53. )
  54.  
  55. let alert = SCLAlertView(appearance: appearance)
  56. alert.addButton("Inserir minha cidade natal") {
  57. let autocompleteController = GMSAutocompleteViewController()
  58. autocompleteController.delegate = self
  59. self.present(autocompleteController, animated: true, completion: nil)
  60. }
  61. //alert.showWarning("Atenção!", subTitle: "Como você fez login com facebook, é necessário uma cidade natal para continuar. Para desfrutar totalmente do Heply, insira sua cidade natal!", animationStyle: .topToBottom)
  62. }
  63. }
  64.  
  65.  
  66.  
  67. activityIndicator.type = .ballScaleRippleMultiple
  68. activityIndicator.startAnimating()
  69. view.isUserInteractionEnabled = false
  70. self.tabBarController?.tabBar.isUserInteractionEnabled = false
  71. isFirst = true
  72. callLoad()
  73.  
  74. refreshControl.tintColor = UIColor(red: 43.0/255.0, green: 69.0/255.0, blue: 112.0/255.0, alpha: 1.0)
  75. refreshControl.addTarget(self, action: #selector(FeedViewController.callLoad), for: .valueChanged)
  76. tableView.addSubview(refreshControl)
  77. self.tabBarController?.delegate = self
  78. }
  79.  
  80. override func viewWillAppear(_ animated: Bool) {
  81. self.tabBarController?.tabBar.isHidden = false
  82. }
  83.  
  84. override func viewDidAppear(_ animated: Bool) {
  85. self.tableViewGoToTop = true
  86. }
  87.  
  88. override func viewWillDisappear(_ animated: Bool) {
  89. self.tableViewGoToTop = false
  90. self.tabBarController?.tabBar.isHidden = true
  91. }
  92.  
  93. //MARK: - TableView
  94. func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
  95.  
  96. if !createPostTextViewState {
  97. performSegue(withIdentifier: "ShowPostSegue", sender: nil)
  98. } else {
  99. self.view.endEditing(true)
  100. }
  101.  
  102. tableView.deselectRow(at: indexPath, animated: true)
  103. }
  104.  
  105. func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
  106. return (posts.count + 1)
  107. }
  108.  
  109. func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
  110. if (indexPath.row == 0){
  111. return createPostHeight
  112. }
  113. else{
  114. return 266
  115. }
  116. }
  117.  
  118. func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
  119. if (indexPath.row == 0){
  120. guard let cell = tableView.dequeueReusableCell(withIdentifier: "CreatePostTableViewCell") as? CreatePostTableViewCell else {
  121. print("Problema ao utilizar a celula do storyboard")
  122.  
  123. return UITableViewCell()
  124. }
  125.  
  126. cell.dataTextView.customTextViewDelegate = self
  127.  
  128. if let image = selectedImage {
  129. cell.postImageView.image = image
  130. }
  131. else{
  132. //print ("erro no cellforrow")
  133. }
  134. cell.delegate = self
  135. if (Account.currentUser.profileImage == nil){
  136. cell.profileImageView.image = nil
  137. }
  138. else{
  139. cell.profileImageView.loadImageUsingCacheWithUrlString(Account.currentUser.profileImage!)
  140. }
  141. return cell
  142. }
  143. else{
  144. let index = indexPath.row - 1
  145.  
  146. guard let cell = tableView.dequeueReusableCell(withIdentifier: "PostTableViewCell") as? PostTableViewCell else {
  147. print("Problema ao utilizar a celula do storyboard")
  148.  
  149. return UITableViewCell()
  150. }
  151. cell.delegate = self
  152. cell.row = indexPath.row - 1
  153.  
  154. cell.dataLabel.text = posts[index].data
  155. cell.nameLabel.text = posts[index].name
  156. cell.cityLabel.text = posts[index].localization
  157. if (Int (posts[index].answers!) == 1){
  158. cell.answersLabel.text = "\(posts[index].answers!) resposta"
  159.  
  160. }
  161. else{
  162. cell.answersLabel.text = "\(posts[index].answers!) respostas"
  163.  
  164. }
  165. cell.timeAgoLabel.text = FeedFunctions.getTimeAgo(oldDate: posts[index].date!)
  166.  
  167. cell.profileImageView.loadImageUsingCacheWithUrlString(posts[index].profileImage!)
  168.  
  169. if (posts[index].postImage! != ""){
  170. cell.imagePostImageView.loadImageUsingCacheWithUrlString(posts[index].postImage!)
  171. }
  172. else{
  173. cell.imagePostImageView.image = nil
  174. }
  175.  
  176. cell.layer.cornerRadius = 13
  177. cell.layer.masksToBounds = true
  178. cell.layer.shadowColor = UIColor.white.cgColor
  179. cell.layer.shadowOpacity = 0.4
  180. cell.layer.shadowOffset = CGSize(width: CGFloat(0.5), height: CGFloat(3))
  181. cell.layer.shadowRadius = 2
  182. return cell
  183. }
  184. }
  185. //MARK: - ImagePicker
  186. func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]){
  187. if let image = info[UIImagePickerControllerOriginalImage] as? UIImage{
  188. //mandar imagem de volta pra celula
  189. selectedImage = image
  190. let indexPath = IndexPath(row:0, section:0)
  191. let postCell = self.tableView.cellForRow(at: indexPath) as! CreatePostTableViewCell
  192. postCell.postImageView.image = image
  193. updateHeightCell (height: 189)
  194. }
  195. else{
  196. print ("error select image")
  197. }
  198. self.dismiss(animated: true, completion: nil)
  199. }
  200.  
  201. //MARK: - Functions
  202. func tabBarController(_ tabBarController: UITabBarController, didSelect viewController: UIViewController) {
  203. if (tabBarController.selectedIndex == 0){
  204. if (tableViewGoToTop){
  205. self.tableView.setContentOffset(CGPoint.zero, animated: true)
  206. }
  207. else {
  208. tableViewGoToTop = true
  209. }
  210. }
  211. }
  212.  
  213. func segueForProfile (row: Int){
  214. performSegue(withIdentifier: "SegueForProfile", sender: row)
  215. }
  216.  
  217. func updateHeightCell (height: CGFloat){
  218. if (createPostHeight < 103){
  219. self.createPostHeight = height
  220. }
  221. let currentOffset = tableView?.contentOffset
  222. UIView.setAnimationsEnabled(false)
  223. tableView?.beginUpdates()
  224. tableView?.endUpdates()
  225. UIView.setAnimationsEnabled(true)
  226. tableView?.setContentOffset(currentOffset!, animated: false)
  227. }
  228.  
  229. func setNewPost(data: String, category: String) {
  230. dictionaryPost.removeAll()
  231. dictionaryPost["data"] = data
  232. dictionaryPost["date"] = FeedFunctions.getDate()
  233. dictionaryPost["category"] = category
  234. dictionaryPost["answers"] = "0"
  235. dictionaryPost["name"] = Account.currentUser.name
  236. dictionaryPost["profileImage"] = Account.currentUser.profileImage
  237. dictionaryPost["userUID"] = Account.currentUser.userUID
  238. dictionaryPost["city"] = Account.currentUser.city
  239.  
  240. if (selectedImage == nil){
  241. dictionaryPost["postImage"] = ""
  242. }
  243. else{
  244. FirebaseConnection.uploadImageStorage (imagePost: selectedImage!){(newURL) -> (Void) in
  245. if let url = newURL {
  246. self.dictionaryPost["postImage"] = url
  247. FirebaseConnection.setPost(post: self.dictionaryPost)
  248. }
  249. }
  250. }
  251. }
  252.  
  253. func selectImage() {
  254. let photo = UIImagePickerController()
  255. photo.delegate = self
  256. photo.sourceType = UIImagePickerControllerSourceType.photoLibrary
  257. photo.allowsEditing = false
  258. self.present(photo, animated: true){}
  259. }
  260.  
  261. func attHeight(height: CGFloat) {
  262. self.createPostHeight = height
  263. tableView.reloadData()
  264. }
  265.  
  266. func callLoad(){
  267. FirebaseConnection.getPosts { (newPosts) -> (Void) in
  268. if let posts = newPosts {
  269. self.posts.removeAll()
  270. self.posts = posts
  271. self.posts.sort(by: { (t1, t2) -> Bool in
  272. t1.date! > t2.date!
  273. })
  274. }
  275. else{
  276. self.posts.removeAll()
  277. }
  278. //UIView.transition(with: self.tableView, duration: 0.3, options: .transitionCrossDissolve, animations: {self.tableView.reloadData()}, completion: nil)
  279. if self.refreshControl.isRefreshing {
  280. self.tableView.reloadData()
  281. Reachability.sleep(1){
  282. self.refreshControl.endRefreshing()
  283. }
  284. }
  285. if self.isFirst! {
  286. self.view.isUserInteractionEnabled = true
  287. self.tabBarController?.tabBar.isUserInteractionEnabled = true
  288. self.activityIndicator.stopAnimating()
  289. UIView.transition(with: self.tableView, duration: 0.2, options: .transitionCrossDissolve, animations: {self.tableView.reloadData()}, completion: nil)
  290. self.isFirst = false
  291. }
  292. }
  293. }
  294.  
  295. override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
  296. if segue.identifier == "CreatePostSegue" {
  297. _ = segue.destination as! CreatePostViewController
  298. }
  299. if segue.identifier == "ShowPostSegue" {
  300. let destination = segue.destination as! ShowPostViewController
  301. let indexPost = (self.tableView.indexPathForSelectedRow?.row)
  302. destination.varFromSegue = (self.posts[indexPost! - 1], true)
  303. destination.delegate = self
  304. }
  305. if (segue.identifier == "SegueForProfile"){
  306. let destination = segue.destination as! ProfileViewController
  307. if let row = sender as? Int{
  308. destination.varFromSegue = (self.posts[row], true)
  309.  
  310. }
  311. }
  312. }
  313.  
  314. func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
  315. self.view.endEditing(true)
  316. }
  317.  
  318. override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
  319. self.view.endEditing(true)
  320. }
  321. }
  322.  
  323. extension FeedViewController: GMSAutocompleteViewControllerDelegate {
  324. func viewController(_ viewController: GMSAutocompleteViewController, didAutocompleteWith place: GMSPlace) {
  325. requisition.saveCityAccount(place.name, place.placeID, Account.currentUser.userUID!) { (newBool) -> (Void) in
  326. if newBool != nil {}
  327. }
  328. dismiss(animated: true, completion: nil)
  329. }
  330.  
  331. func viewController(_ viewController: GMSAutocompleteViewController, didFailAutocompleteWithError error: Error) {
  332. print("Error: ", error.localizedDescription)
  333. }
  334.  
  335. func wasCancelled(_ viewController: GMSAutocompleteViewController) {
  336. // dismiss(animated: true, completion: nil)
  337. }
  338.  
  339. func didRequestAutocompletePredictions(_ viewController: GMSAutocompleteViewController) {
  340. UIApplication.shared.isNetworkActivityIndicatorVisible = true
  341. }
  342.  
  343. func didUpdateAutocompletePredictions(_ viewController: GMSAutocompleteViewController) {
  344. UIApplication.shared.isNetworkActivityIndicatorVisible = false
  345. }
  346. }
  347.  
  348. extension FeedViewController: CustomTextViewDelegate {
  349. func editingStatus(_ state: Bool) {
  350. createPostTextViewState = state
  351. }
  352. }
  353.  
  354.  
  355. // GMSPlacesClient.shared().autocompleteQuery((textField?.text)!, bounds: nil, filter: nil, callback: {
  356. // (result, error) in
  357. // if error != nil {
  358. // print(error!)
  359. // } else {
  360. // print(result!)
  361. // }
  362. // })
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement