Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //
- // FeedViewController.swift
- // Heply
- //
- // Created by marllons on 30/05/17.
- // Copyright © 2017 ifce. All rights reserved.
- //
- import UIKit
- import FirebaseAuth
- import GooglePlaces
- import GooglePlacePicker
- import SCLAlertView
- import NVActivityIndicatorView
- protocol CustomTextViewDelegate: class {
- func editingStatus(_ state: Bool)
- }
- class FeedViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, SendDataBack, CreateCellDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate, UITabBarControllerDelegate {
- //MARK: - Outlets
- @IBOutlet weak var tableView: UITableView!
- @IBOutlet weak var activityIndicator: NVActivityIndicatorView!
- //MARK: - Actions
- //MARK: - Variables
- var selectedImage: UIImage?
- var posts = [Post]()
- let refreshControl = UIRefreshControl()
- let requisition = FirebaseRequisition()
- var createPostHeight = CGFloat(102)
- var dictionaryPost = [String: String]()
- let transition = CATransition()
- var isFirst: Bool?
- var tableViewGoToTop = true
- var createPostTextViewState: Bool = false
- //MARK: - ViewDidLoad
- override func viewDidLoad() {
- super.viewDidLoad()
- // appDelegate.handleLogout(self)
- SwipeView.desativateTimer()
- //Requisiçao para salvar dados do usuário no singleton
- requisition.requisitonLogin((Auth.auth().currentUser?.uid)!){(newBool) -> (Void) in
- if !(newBool!){
- let appearance = SCLAlertView.SCLAppearance(
- showCloseButton: false
- )
- let alert = SCLAlertView(appearance: appearance)
- alert.addButton("Inserir minha cidade natal") {
- let autocompleteController = GMSAutocompleteViewController()
- autocompleteController.delegate = self
- self.present(autocompleteController, animated: true, completion: nil)
- }
- //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)
- }
- }
- activityIndicator.type = .ballScaleRippleMultiple
- activityIndicator.startAnimating()
- view.isUserInteractionEnabled = false
- self.tabBarController?.tabBar.isUserInteractionEnabled = false
- isFirst = true
- callLoad()
- refreshControl.tintColor = UIColor(red: 43.0/255.0, green: 69.0/255.0, blue: 112.0/255.0, alpha: 1.0)
- refreshControl.addTarget(self, action: #selector(FeedViewController.callLoad), for: .valueChanged)
- tableView.addSubview(refreshControl)
- self.tabBarController?.delegate = self
- }
- override func viewWillAppear(_ animated: Bool) {
- self.tabBarController?.tabBar.isHidden = false
- }
- override func viewDidAppear(_ animated: Bool) {
- self.tableViewGoToTop = true
- }
- override func viewWillDisappear(_ animated: Bool) {
- self.tableViewGoToTop = false
- self.tabBarController?.tabBar.isHidden = true
- }
- //MARK: - TableView
- func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
- if !createPostTextViewState {
- performSegue(withIdentifier: "ShowPostSegue", sender: nil)
- } else {
- self.view.endEditing(true)
- }
- tableView.deselectRow(at: indexPath, animated: true)
- }
- func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
- return (posts.count + 1)
- }
- func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
- if (indexPath.row == 0){
- return createPostHeight
- }
- else{
- return 266
- }
- }
- func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
- if (indexPath.row == 0){
- guard let cell = tableView.dequeueReusableCell(withIdentifier: "CreatePostTableViewCell") as? CreatePostTableViewCell else {
- print("Problema ao utilizar a celula do storyboard")
- return UITableViewCell()
- }
- cell.dataTextView.customTextViewDelegate = self
- if let image = selectedImage {
- cell.postImageView.image = image
- }
- else{
- //print ("erro no cellforrow")
- }
- cell.delegate = self
- if (Account.currentUser.profileImage == nil){
- cell.profileImageView.image = nil
- }
- else{
- cell.profileImageView.loadImageUsingCacheWithUrlString(Account.currentUser.profileImage!)
- }
- return cell
- }
- else{
- let index = indexPath.row - 1
- guard let cell = tableView.dequeueReusableCell(withIdentifier: "PostTableViewCell") as? PostTableViewCell else {
- print("Problema ao utilizar a celula do storyboard")
- return UITableViewCell()
- }
- cell.delegate = self
- cell.row = indexPath.row - 1
- cell.dataLabel.text = posts[index].data
- cell.nameLabel.text = posts[index].name
- cell.cityLabel.text = posts[index].localization
- if (Int (posts[index].answers!) == 1){
- cell.answersLabel.text = "\(posts[index].answers!) resposta"
- }
- else{
- cell.answersLabel.text = "\(posts[index].answers!) respostas"
- }
- cell.timeAgoLabel.text = FeedFunctions.getTimeAgo(oldDate: posts[index].date!)
- cell.profileImageView.loadImageUsingCacheWithUrlString(posts[index].profileImage!)
- if (posts[index].postImage! != ""){
- cell.imagePostImageView.loadImageUsingCacheWithUrlString(posts[index].postImage!)
- }
- else{
- cell.imagePostImageView.image = nil
- }
- cell.layer.cornerRadius = 13
- cell.layer.masksToBounds = true
- cell.layer.shadowColor = UIColor.white.cgColor
- cell.layer.shadowOpacity = 0.4
- cell.layer.shadowOffset = CGSize(width: CGFloat(0.5), height: CGFloat(3))
- cell.layer.shadowRadius = 2
- return cell
- }
- }
- //MARK: - ImagePicker
- func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]){
- if let image = info[UIImagePickerControllerOriginalImage] as? UIImage{
- //mandar imagem de volta pra celula
- selectedImage = image
- let indexPath = IndexPath(row:0, section:0)
- let postCell = self.tableView.cellForRow(at: indexPath) as! CreatePostTableViewCell
- postCell.postImageView.image = image
- updateHeightCell (height: 189)
- }
- else{
- print ("error select image")
- }
- self.dismiss(animated: true, completion: nil)
- }
- //MARK: - Functions
- func tabBarController(_ tabBarController: UITabBarController, didSelect viewController: UIViewController) {
- if (tabBarController.selectedIndex == 0){
- if (tableViewGoToTop){
- self.tableView.setContentOffset(CGPoint.zero, animated: true)
- }
- else {
- tableViewGoToTop = true
- }
- }
- }
- func segueForProfile (row: Int){
- performSegue(withIdentifier: "SegueForProfile", sender: row)
- }
- func updateHeightCell (height: CGFloat){
- if (createPostHeight < 103){
- self.createPostHeight = height
- }
- let currentOffset = tableView?.contentOffset
- UIView.setAnimationsEnabled(false)
- tableView?.beginUpdates()
- tableView?.endUpdates()
- UIView.setAnimationsEnabled(true)
- tableView?.setContentOffset(currentOffset!, animated: false)
- }
- func setNewPost(data: String, category: String) {
- dictionaryPost.removeAll()
- dictionaryPost["data"] = data
- dictionaryPost["date"] = FeedFunctions.getDate()
- dictionaryPost["category"] = category
- dictionaryPost["answers"] = "0"
- dictionaryPost["name"] = Account.currentUser.name
- dictionaryPost["profileImage"] = Account.currentUser.profileImage
- dictionaryPost["userUID"] = Account.currentUser.userUID
- dictionaryPost["city"] = Account.currentUser.city
- if (selectedImage == nil){
- dictionaryPost["postImage"] = ""
- }
- else{
- FirebaseConnection.uploadImageStorage (imagePost: selectedImage!){(newURL) -> (Void) in
- if let url = newURL {
- self.dictionaryPost["postImage"] = url
- FirebaseConnection.setPost(post: self.dictionaryPost)
- }
- }
- }
- }
- func selectImage() {
- let photo = UIImagePickerController()
- photo.delegate = self
- photo.sourceType = UIImagePickerControllerSourceType.photoLibrary
- photo.allowsEditing = false
- self.present(photo, animated: true){}
- }
- func attHeight(height: CGFloat) {
- self.createPostHeight = height
- tableView.reloadData()
- }
- func callLoad(){
- FirebaseConnection.getPosts { (newPosts) -> (Void) in
- if let posts = newPosts {
- self.posts.removeAll()
- self.posts = posts
- self.posts.sort(by: { (t1, t2) -> Bool in
- t1.date! > t2.date!
- })
- }
- else{
- self.posts.removeAll()
- }
- //UIView.transition(with: self.tableView, duration: 0.3, options: .transitionCrossDissolve, animations: {self.tableView.reloadData()}, completion: nil)
- if self.refreshControl.isRefreshing {
- self.tableView.reloadData()
- Reachability.sleep(1){
- self.refreshControl.endRefreshing()
- }
- }
- if self.isFirst! {
- self.view.isUserInteractionEnabled = true
- self.tabBarController?.tabBar.isUserInteractionEnabled = true
- self.activityIndicator.stopAnimating()
- UIView.transition(with: self.tableView, duration: 0.2, options: .transitionCrossDissolve, animations: {self.tableView.reloadData()}, completion: nil)
- self.isFirst = false
- }
- }
- }
- override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
- if segue.identifier == "CreatePostSegue" {
- _ = segue.destination as! CreatePostViewController
- }
- if segue.identifier == "ShowPostSegue" {
- let destination = segue.destination as! ShowPostViewController
- let indexPost = (self.tableView.indexPathForSelectedRow?.row)
- destination.varFromSegue = (self.posts[indexPost! - 1], true)
- destination.delegate = self
- }
- if (segue.identifier == "SegueForProfile"){
- let destination = segue.destination as! ProfileViewController
- if let row = sender as? Int{
- destination.varFromSegue = (self.posts[row], true)
- }
- }
- }
- func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
- self.view.endEditing(true)
- }
- override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
- self.view.endEditing(true)
- }
- }
- extension FeedViewController: GMSAutocompleteViewControllerDelegate {
- func viewController(_ viewController: GMSAutocompleteViewController, didAutocompleteWith place: GMSPlace) {
- requisition.saveCityAccount(place.name, place.placeID, Account.currentUser.userUID!) { (newBool) -> (Void) in
- if newBool != nil {}
- }
- dismiss(animated: true, completion: nil)
- }
- func viewController(_ viewController: GMSAutocompleteViewController, didFailAutocompleteWithError error: Error) {
- print("Error: ", error.localizedDescription)
- }
- func wasCancelled(_ viewController: GMSAutocompleteViewController) {
- // dismiss(animated: true, completion: nil)
- }
- func didRequestAutocompletePredictions(_ viewController: GMSAutocompleteViewController) {
- UIApplication.shared.isNetworkActivityIndicatorVisible = true
- }
- func didUpdateAutocompletePredictions(_ viewController: GMSAutocompleteViewController) {
- UIApplication.shared.isNetworkActivityIndicatorVisible = false
- }
- }
- extension FeedViewController: CustomTextViewDelegate {
- func editingStatus(_ state: Bool) {
- createPostTextViewState = state
- }
- }
- // GMSPlacesClient.shared().autocompleteQuery((textField?.text)!, bounds: nil, filter: nil, callback: {
- // (result, error) in
- // if error != nil {
- // print(error!)
- // } else {
- // print(result!)
- // }
- // })
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement