// HomeViewController.swift // GMERemittance // // Created by Kushal on 12/11/17. // Copyright © 2017 Gobal Money Express Co. Ltd. All rights reserved. // import UIKit import Social import FacebookShare import FBSDKShareKit class HomeViewController: UIViewController, TableViewCellDelegate, FBSDKSharingDelegate { enum TableViewCells: Int { case balance = 0 case collection = 1 case status = 2 case social = 3 case loadMore = 4 } private var isTopMenuVisible: Bool = false @IBOutlet weak var topMenuView: UIView! @IBOutlet weak var tableViewTopConstraint: NSLayoutConstraint! @IBOutlet weak var buttonMenuItem0: UIButton! @IBOutlet weak var buttonMenuItem1: UIButton! @IBOutlet weak var buttonMenuItem2: UIButton! @IBOutlet weak var labelMenuItem0: UILabel! @IBOutlet weak var labelMenuItem1: UILabel! @IBOutlet weak var labelMenuItem2: UILabel! private let homeviewmodel = HomeViewModel() private let socialfeedviewmodel = SocialFeedViewModel() private let profileViewModel = ProfileViewModel() private let notificationviewmodel = NotificationViewModel() var page: Int = 0 var size: Int = 20 var sections: [TableViewCells] = [.balance, .collection, .status, .social, .loadMore] private var activityIndicator: UIActivityIndicatorView = UIActivityIndicatorView() private let imagePicker = UIImagePickerController() var showAllCollectionViewCells: Bool? private let collectionViewItemsPerRow: CGFloat = 2 private let insetForCollectionView: CGFloat = 5.0 var numberCellsInCollectionView: Int? private var longPressGesture: UILongPressGestureRecognizer! private var collectionViewMenuIndexArray: [Int]! private var collectionViewMenuIconArray: [Int: String] = [0: "send-money", 1: "mobile-recharge", 2: "rate-today", 3: "track-transfer", 4: "transaction-statement", 5: "wallet-transfer", 6: "show-more"] private var collectionViewMenuNameArray: [Int: String] = [0: "Send Money", 1: "Mobile Recharge", 2: "Today's Rate", 3: "Track Your Transfer", 4: "Transaction Statement", 5: "Wallet to Wallet Transfer", 6: "More"] /* MORE Button is placed at the end of the array (position 7, index 6) and it is switched with the element at position 4 (index 3) when showing some/ all of the menu options */ @IBOutlet weak var imageViewUserImage: UIImageView! @IBOutlet weak var tableView: UITableView! private var cell: TableViewCell! /*------ 0 => Text Status ------ 1 => Image Upload ------ 2 => Edit Status */ private var statusUploadMode:Int? //IMAGE OR TEXT STATUS UPLOAD private var editablePostIndex: Int! private var selectedCell:Int? //SELECTED CELL private var selectedImage:UIImage? //EDIT IMAGE FOR REMOVE OR DELETE private var postStatus:String? // private var heartStatus:Bool? private var socialStatus:Bool? private var likeCount:Int? private var tappedIndex: Int? private var allowFetchRequest: Bool = true private var newFeedsWillBeAppended: Bool = false private var refreshControl: UIRefreshControl! private var arrayIndexPath = [IndexPath] () private var showNotificationParameter: Bool = false private var editedIndex: Int! //--SETUP NAVBAR WHEN VIEW APPEARS PLUS RELOAD THE SOCIAL FEED WITH LOCAL DATA IF EXISTS override func viewWillAppear(_ animated: Bool) { editedIndex = nil // setUpAnotherLoginListener(genericviewmodel: socialfeedviewmodel) setUpAnotherLoginListener(genericviewmodel: profileViewModel) setUpNetworkListener() super.viewWillAppear(true) self.tabBarController?.tabBar.isHidden = false setNavBar() setActionBarIcons(showNotificationParameter: false) // setUpRefreshControl() bindUserStatusToUI() profileViewModel.fetchUserInfo(userId: nil) // socialfeedviewmodel.socialFeedsRxValue.value = nil // // socialfeedviewmodel.setAccessType(accessType: "public") // self.bindFeedsDataToUI() tableView.reloadSections(NSIndexSet(index: 3) as IndexSet, with: .none) if tappedIndex != nil { tableView.scrollToRow(at: IndexPath(row: tappedIndex!, section: 3), at: UITableViewScrollPosition.bottom, animated: true) } notificationBind() } override func viewWillDisappear(_ animated: Bool) { super.viewWillAppear(animated) self.navigationController?.navigationBar.topItem?.title = "" } func setUpRefreshControl() { refreshControl = UIRefreshControl() refreshControl.backgroundColor = UIColor(white: 0.98, alpha: 1.0) refreshControl.tintColor = UIColor.red refreshControl.addTarget(self, action: #selector(refresh(_:)), for: .valueChanged) tableView.addSubview(refreshControl) } @objc func refresh(_ sender: AnyObject) { newFeedsWillBeAppended = false // tableView.cellForRow(at: IndexPath(row: 0, section: 4))?.isHidden = true // socialfeedviewmodel.resetBeforeAfterFeedId() // socialfeedviewmodel.fetchSocialFeeds(isPublic: true, loadMore: false) } //--ALL NAV BAR FUNCTIONS HERE func setNavBar() { self.navigationController?.navigationBar.setBackgroundImage(UIImage(), for: .default) self.navigationController?.navigationBar.shadowImage = UIImage() self.navigationController?.navigationBar.isTranslucent = false self.tabBarController?.navigationItem.hidesBackButton = true let rightButton = UIBarButtonItem(image: UIImage(named: "ic_hamburger"), style: .plain, target: self, action: #selector(showSideMenu)) self.tabBarController?.navigationItem.leftBarButtonItem = rightButton self.tabBarController?.navigationItem.leftBarButtonItem?.tintColor = UIColor.white self.tabBarController?.navigationController?.navigationBar.barTintColor = UIColor(hex:0xec1c24) let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 125, height: 30)) imageView.contentMode = .scaleAspectFit let image = UIImage(named: "ic_gme_new") imageView.image = image self.tabBarController?.navigationItem.titleView = imageView } @objc func showSideMenu() { performSegue(withIdentifier: "showSideMenu", sender: nil) } func isVerifiedUser() -> Bool { return UserDefaults.standard.object(forKey: "com.gmeremit.isVerified") as! Bool } /** Update User data in view */ func bindUserStatusToUI() { profileViewModel.userDataAvailable.value = nil profileViewModel.userDataAvailable.bind{ [weak self] in guard $0 != nil else { return } if $0! { let verified = UserDefaults.standard.object(forKey: "com.gmeremit.isVerified") as! Bool if !verified { let isVerified = self?.profileViewModel.isVerified() if isVerified! { UserDefaults.standard.set(isVerified, forKey: "com.gmeremit.isVerified") } } UserDefaults.standard.set(self?.profileViewModel.getAvailableBalance(), forKey: "com.gmeremit.balance") UserDefaults.standard.set(self?.profileViewModel.getRewardPoint(), forKey: "com.gmeremit.rewardPoint") UserDefaults.standard.set(self?.profileViewModel.getWalletNumber(), forKey: "com.gmeremit.walletNumber") /// TABLE RELOADED self?.tableView.reloadData() } self?.profileViewModel.userDataAvailable.value = nil } } func notificationBind(){ notificationviewmodel.fetchNotification(page: self.page, size: self.size) notificationviewmodel.notificationFetch.bind{ [weak self] in guard $0 != nil else { return } guard $0! else { //self?.popUpMessageError(value: 10, message: (self?.notificationviewmodel.getErrorMessage())!) return } //Update the view self?.enableUserInteractions() if self?.activityIndicator != nil { self?.dismissActivityIndicator(activityIndicator: (self?.activityIndicator)!) } if (self?.notificationviewmodel.showNotification())!{ self?.showNotificationParameter = true self?.setActionBarIcons(showNotificationParameter: true) } else { self?.showNotificationParameter = false self?.setActionBarIcons(showNotificationParameter: false) } } } func registerCMUser() { let appDelegate = UIApplication.shared.delegate as! AppDelegate appDelegate.notificationSet.bind { [unowned self] in guard $0 != nil else { return } self.homeviewmodel.cmRegistrationId(cmRegistrationId: appDelegate.cmRegistrationId!) } } /** @developer : Suraj Shrestha @date : 2018/02/12 @des : Add action bar icons i.e notification and support */ func setActionBarIcons(showNotificationParameter: Bool){ let supportImage = UIImage(named: "ic_support")?.withRenderingMode(.alwaysOriginal) let supportButton = UIBarButtonItem(image:supportImage, style: .plain, target: self, action: #selector(showSupport)) let notificationImage: UIImage! if showNotificationParameter { notificationImage = UIImage(named: "ic_notificationDot")?.withRenderingMode(.alwaysOriginal) } else { notificationImage = UIImage(named: "ic_notification")?.withRenderingMode(.alwaysOriginal) } let notificationButton = UIBarButtonItem(image: notificationImage, style: .plain, target: self, action: #selector(showNotification)) self.tabBarController?.navigationItem.rightBarButtonItems=[notificationButton,supportButton] } /** @developer : Suraj Shrestha @date : 2018/02/12 @des : Show support actions */ @objc func showSupport() { let alert = UIAlertController(title:nil, message:"We are there to help you \n (Available time 10:00AM - 6:00PM)", preferredStyle: .actionSheet) alert.view.subviews.last?.subviews.last?.backgroundColor = UIColor.darkGray let liveChat = UIAlertAction(title: "Live Chat", style: .default) { UIAlertAction in } let contactNumber = UIAlertAction(title: "1588 6864", style: .default) { UIAlertAction in self.startCall(contactNumber: "1588 6864") } let supportEmail = UIAlertAction(title: "support@gmeremit.com", style: .default) { UIAlertAction in let storyboard = UIStoryboard.init(name: "Home", bundle: Bundle.main) if let messageViewController = storyboard.instantiateViewController(withIdentifier: "message") as? MessageComposeViewController { messageViewController.supportIndex = 0 self.navigationController!.pushViewController(messageViewController, animated: true) } } liveChat.setValue(UIImage(named:"ic_live_chat")?.withRenderingMode(.alwaysOriginal),forKey:"image") contactNumber.setValue(UIImage(named:"ic_call")?.withRenderingMode(.alwaysOriginal),forKey:"image") supportEmail.setValue(UIImage(named:"ic_email")?.withRenderingMode(.alwaysOriginal),forKey:"image") // TODO: have to enable when zendesk is provided // alert.addAction(liveChat) alert.addAction(contactNumber) alert.addAction(supportEmail) alert.view.tintColor = UIColor.red alert.view.subviews.last?.subviews.last?.layer.cornerRadius = 10 alert.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.cancel, handler: nil)) present(alert, animated: true, completion: nil) } func startCall(contactNumber: String){ if let url = URL(string: "tel://\(contactNumber.removeWhitespacesInBetween())"), UIApplication.shared.canOpenURL(url) { if #available(iOS 10, *) { UIApplication.shared.open(url) } else { UIApplication.shared.openURL(url) } } } @objc func showNotification(){ performSegue(withIdentifier: "notification", sender: nil) } // func checkNetwork() { // if !Reachability.isConnectedToNetwork() { // self.popUpMessage(value: 15) // } // } func setUpNetworkListener() { // socialfeedviewmodel.internetConnection.value = nil // socialfeedviewmodel.internetConnection.bind { [unowned self] in // guard $0 != nil else { // return // } // self.enableUserInteractions() // self.popUpMessage(value: 15) // } } override func viewDidLoad() { super.viewDidLoad() setupDelegates() hideKeyboardWhenTappedAround() setUpRefreshControl() if numberCellsInCollectionView == nil { numberCellsInCollectionView = 4 } if showAllCollectionViewCells == nil { showAllCollectionViewCells = false } /* Checks if the user's custom menu is available or not */ if let menuArray = UserDefaults.standard.array(forKey: "com.gmeremit.collectionViewMenuIndexArray") as? [Int] { collectionViewMenuIndexArray = menuArray /* While loading the app (but not from myStoryViewController), MORE button should be shown */ if numberCellsInCollectionView == 4 { if collectionViewMenuIndexArray[3] != 6 { collectionViewMenuIndexArray.swapAt(3, 6) } } else if numberCellsInCollectionView == 6 { if collectionViewMenuIndexArray[3] == 6 { collectionViewMenuIndexArray.swapAt(3, 6) } } } else { collectionViewMenuIndexArray = [0, 1, 2, 6, 4, 5, 3] UserDefaults.standard.set(collectionViewMenuIndexArray, forKey: "com.gmeremit.collectionViewMenuIndexArray") } longPressGesture = UILongPressGestureRecognizer(target: self, action: #selector(self.handleLongGesture(gesture:))) imagePicker.delegate = self tableView.tableFooterView = UIView() registerCMUser() if UserDefaults.standard.bool(forKey: "com.gmeremit.showImageAlert") { self.addUserProfileImage() } } private func setupDelegates() { tableView.delegate = self tableView.dataSource = self } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { switch segue.identifier { case "statusUpdate"?: let statusUploadViewController = segue.destination as! StatusUploadViewController statusUploadViewController.statusUploadMode = statusUploadMode statusUploadViewController.editablePostIndex = editablePostIndex statusUploadViewController.socialfeedviewmodel = socialfeedviewmodel statusUploadViewController.showNotificationParameter = showNotificationParameter case "showLikedBy"?: let likedByViewController = segue.destination as! LikesViewController likedByViewController.socialfeedviewmodel = socialfeedviewmodel likedByViewController.tappedIndex = tappedIndex case "showCommentsBy"?: let commentsViewController = segue.destination as! CommentsViewController commentsViewController.socialfeedviewmodel = socialfeedviewmodel commentsViewController.tappedIndex = tappedIndex case "myStory"?: let myStoryViewController = segue.destination as! MyStoryViewController myStoryViewController.socialfeedviewmodel = socialfeedviewmodel myStoryViewController.showNotificationParameter = showNotificationParameter case "notification"?: let notificationViewController = segue.destination as! NotificationViewController notificationViewController.socialfeedviewmodel = socialfeedviewmodel default: return } } } /*---------------ALL ACTIONS RELATED TO SOCIAL WALL HERE------------ */ extension HomeViewController { //UPLOAD TEXT AS STATUS @objc func uploadTextStatus(_ sender: TableViewCell) { statusUploadMode = 0 self.performSegue(withIdentifier: "statusUpdate", sender: nil) } //UPLOAD IMAGE AS STATUS @objc func uploadImageStatus(_ sender: TableViewCell) { statusUploadMode = 1 self.performSegue(withIdentifier: "statusUpdate", sender: nil) } //DATA BINDING func bindFeedsDataToUI() { socialfeedviewmodel.socialFeedsRxValue.bind { [weak self] in guard $0 != nil, self?.socialfeedviewmodel != nil else { return } guard $0! != 0 else { //self.popUpMessageError(value: 10, message: self.socialfeedviewmodel.getErrorMessage()) self?.socialfeedviewmodel.socialFeedsRxValue.value = nil return } switch $0! { case socialWallCode.fetchPostsPublic.rawValue: let count = self?.socialfeedviewmodel.getPublicSocialFeedsCount() if count! > 0 { if (self?.newFeedsWillBeAppended)! { self?.arrayIndexPath.removeAll() self?.tableView.beginUpdates() let currentCount = self?.socialfeedviewmodel.getCurrentlyFetchedFeedCount() for i in 0...(self?.socialfeedviewmodel.getCurrentlyFetchedFeedCount())!-1 { self?.arrayIndexPath.append(IndexPath.init(row: count! - currentCount! + i, section: 3)) } self?.tableView.insertRows(at: (self?.arrayIndexPath)!, with: .automatic) self?.tableView.endUpdates() self?.tableView.cellForRow(at: IndexPath(row: 0, section: 4))?.isHidden = false } else { if (self?.refreshControl.isRefreshing)! { self?.refreshControl.endRefreshing() } self?.tableView.reloadSections(NSIndexSet(index: 3) as IndexSet, with: .none) self?.tableView.reloadSections(NSIndexSet(index: 4) as IndexSet, with: .none) } } case socialWallCode.deletePost.rawValue: self?.socialfeedviewmodel.removeSocialFeed(atIndex: (self?.tappedIndex!)!) self?.tableView.deleteRows(at: [IndexPath(item: (self?.tappedIndex!)!, section: 3)], with: .automatic) case socialWallCode.likeUnlikePost.rawValue: self?.socialfeedviewmodel.updateSocialFeedArrayLikeNumber(atIndex: (self?.tappedIndex!)!) self?.tableView.reloadRows(at: [IndexPath(item: (self?.tappedIndex!)!, section: 3)], with: UITableViewRowAnimation.automatic) case socialWallCode.reportPost.rawValue: self?.reportSendAlert() case socialWallCode.createUpdatePost.rawValue: self?.dismissActivityIndicator(activityIndicator: (self?.activityIndicator)!) self?.tableView.reloadSections(IndexSet(integer: 3), with: UITableViewRowAnimation.automatic) guard let index = self?.editedIndex else { return } self?.tableView.scrollToRow(at: IndexPath(row: index, section: 3), at: UITableViewScrollPosition.none, animated: false) self?.editedIndex = nil let alert = UIAlertController(title:"", message:"This post is made private." , preferredStyle: .actionSheet) self?.present(alert, animated: true, completion: nil) let when = DispatchTime.now() + 2 DispatchQueue.main.asyncAfter(deadline: when){ alert.dismiss(animated: true, completion: nil) } default: return } self?.socialfeedviewmodel.socialFeedsRxValue.value = nil } } /// loadBalance @objc func loadBalanceTap(_ sender: TableViewCell) { guard let navController = self.navigationController else { return } let popUpViewController = UIStoryboard(name: "Home", bundle: nil).instantiateViewController(withIdentifier: "loadBalance") as! LoadBalanceViewController navController.addChildViewController(popUpViewController) popUpViewController.view.frame = navController.view.bounds navController.view.addSubview(popUpViewController.view) popUpViewController.didMove(toParentViewController: navController) } @objc func rewardTap(_ sender: TableViewCell) { let storyboard = UIStoryboard.init(name: "Reward", bundle: Bundle.main) let vController = storyboard.instantiateViewController(withIdentifier: "RewardViewController") as! RewardViewController self.navigationController!.pushViewController(vController, animated: true) } @objc func agentTap(_ sender: TableViewCell) { let storyboard = UIStoryboard.init(name: "Home", bundle: Bundle.main) let vController = storyboard.instantiateViewController(withIdentifier: "PayoutViewController") as! PayoutViewController self.navigationController!.pushViewController(vController, animated: true) } @IBAction func showMyStories(_ sender: Any) { self.performSegue(withIdentifier: "myStory", sender: nil) } //DISPLAY FEEDS ON THE GME WALL func getTableViewCell(indexPath: IndexPath, socialFeed : SocialFeed, mode: Int) -> UITableViewCell { let cell: TableViewCell! switch mode { case 1: cell = tableView.dequeueReusableCell(withIdentifier: "socialCellText", for: indexPath) as! TableViewCell cell.labelStatus.text = socialFeed.feedText cell.labelStatus.textColor = UIColor(red:0.29, green:0.29, blue:0.29, alpha:1.0) case 2: cell = tableView.dequeueReusableCell(withIdentifier: "socialCellImage", for: indexPath) as! TableViewCell cell.imageViewSocial.sd_setImage(with: URL(string: socialFeed.feedImage!)!, placeholderImage: nil, options: [.progressiveDownload,.scaleDownLargeImages], completed: nil) cell.postImageHeight.constant = view.frame.width case 3: cell = tableView.dequeueReusableCell(withIdentifier: "socialCellTextImage", for: indexPath) as! TableViewCell cell.labelStatus.text = socialFeed.feedText cell.labelStatus.textColor = UIColor(red:0.29, green:0.29, blue:0.29, alpha:1.0) cell.imageViewSocial.sd_setImage(with: URL(string: socialFeed.feedImage!)!, placeholderImage: nil, options: [.progressiveDownload,.scaleDownLargeImages], completed: nil) cell.postImageHeight.constant = view.frame.width default: cell = tableView.dequeueReusableCell(withIdentifier: "socialCellTextImage", for: indexPath) as! TableViewCell } cell.layer.borderColor = UIColor(red:0.91, green:0.93, blue:0.95, alpha:1.0).cgColor cell.layer.borderWidth = 2 cell.imageViewUserImage.layer.cornerRadius = cell.imageViewUserImage.frame.height / 2 cell.viewSocialActionConstraint.constant = 58.5 cell.imageViewUserImage.layer.cornerRadius = cell.imageViewUserImage.frame.height / 2 cell.editPostButton?.addTarget(self, action:#selector(showPostOptions(_:)), for:.touchUpInside) cell.heartButton?.addTarget(self, action:#selector(toggleLike(_:)), for:.touchUpInside) cell.likeButton?.addTarget(self, action:#selector(showLikes(_:)), for:.touchUpInside) cell.commentButton?.addTarget(self, action: #selector(showComments(_:)), for: .touchUpInside) //Display USERNAME who has posted the feed cell.labelSocialUsername.text = socialfeedviewmodel.getFullName(feed: socialFeed) //Display USER IMAGE cell.labelUserNameInitial.isHidden = false cell.labelUserNameInitial.backgroundColor = UIColor(hex: 0x2e3192) cell.labelUserNameInitial.layer.cornerRadius = cell.labelUserNameInitial.frame.height / 2 cell.labelUserNameInitial.text = socialFeed.firstName.prefix(1).uppercased() if let userDpString = socialFeed.userDpUrl { if let userDpUrl = URL(string: userDpString) { cell.imageViewUserImage.isHidden = false cell.imageViewUserImage.sd_setImage(with: userDpUrl, placeholderImage: nil, options: [.progressiveDownload,.scaleDownLargeImages], completed: nil) } cell.labelUserNameInitial.isHidden = true } //Display timeStamp (ago date) cell.labelTimeStamp.text = socialFeed.agoDate //Display LIKE status if socialFeed.liked { cell.heartButton?.setImage(UIImage(named:"ic_heartfull"), for: UIControlState.normal) } else { cell.heartButton?.setImage(UIImage(named:"ic_heart"), for: UIControlState.normal) } //Display total number of LIKES if socialFeed.totalLike > 1 { cell.likeButton.setTitle("\(socialFeed.totalLike) Likes", for:UIControlState.normal) } else { cell.likeButton.setTitle("\(socialFeed.totalLike) Like", for:UIControlState.normal) } //Display total number of COMMENTS if socialFeed.totalComment > 1 { cell.commentButton.setTitle(" \(socialFeed.totalComment) Comments", for: UIControlState.normal) } else { cell.commentButton.setTitle(" \(socialFeed.totalComment) Comment", for: UIControlState.normal) } return cell } /** To determine the specific cell for edit the post */ @objc func showPostOptions(_ sender: TableViewCell) { guard let clickedCell = sender.superview?.superview?.superview as? TableViewCell else { return } if let clickedCellIndexPath = tableView.indexPath(for: clickedCell) { enumeratePostOptions(index: clickedCellIndexPath.row) } } /** Alert message for current user */ func enumeratePostOptions(index: Int) { let alert = UIAlertController(title:nil, message:nil, preferredStyle: .actionSheet) if self.socialfeedviewmodel.postBelongsToMe(postIndex: index) { let edit = UIAlertAction(title: "Edit this post", style: .default) { UIAlertAction in self.statusUploadMode = 2 self.editablePostIndex = index self.performSegue(withIdentifier: "statusUpdate", sender: nil) } let delete = UIAlertAction(title: "Delete this post", style: .default) { UIAlertAction in self.deleteConfirmation(postIndex: index) } let moveToPrivate = UIAlertAction(title: "Hide this post from GME Community", style: .default) { UIAlertAction in // self.tappedIndex = index let feedToEdit = self.socialfeedviewmodel.getSocialFeedAt(index: index) if let feedText = feedToEdit.feedText { self.socialfeedviewmodel.updateFeedText(text: feedText) } if let feedImageId = feedToEdit.feedImageId { self.socialfeedviewmodel.setFeedImageId(imageId: feedImageId) } self.editedIndex = index self.showActivityIndicator(activityIndicator: self.activityIndicator) self.socialfeedviewmodel.updateSocialFeed(feed: feedToEdit, index: index, toggle: true) } let cancel = UIAlertAction(title: "Cancel", style: .destructive) { UIAlertAction in } alert.addAction(moveToPrivate) alert.addAction(edit) alert.addAction(delete) alert.addAction(cancel) } else { let report = UIAlertAction(title: "Report", style: .default) { UIAlertAction in self.reportAlert(postIndex: index) } let share = UIAlertAction(title: "Share this post", style: .default) { UIAlertAction in if self.socialfeedviewmodel.getSocialFeedAt(index: index).feedImageId == nil{ self.sharePost(postIndex: index) } } let cancel = UIAlertAction(title: "Cancel", style: .destructive) { UIAlertAction in } alert.addAction(report) if self.socialfeedviewmodel.getSocialFeedAt(index: index).feedImageId == nil{ alert.addAction(share) } alert.addAction(cancel) } present(alert, animated: true, completion: nil) } /** Share the status of GME app to facebook */ func sharePost(postIndex: Int){ let content = FBSDKShareLinkContent() content.contentURL = URL(string: "https://itunes.apple.com/us/app/gme/id1366910197?ls=1&mt=8") // content.hashtag = FBSDKHashtag(string: "#FeelingGood") if let shareText = self.socialfeedviewmodel.getSocialFeedAt(index: postIndex).feedText{ content.quote = shareText } let dialog = FBSDKShareDialog() dialog.fromViewController = self dialog.shareContent = content dialog.delegate = self if !dialog.canShow() { dialog.mode = FBSDKShareDialogMode.native } dialog.show() } func sharer(_ sharer: FBSDKSharing!, didCompleteWithResults results: [AnyHashable : Any]!) { } func sharer(_ sharer: FBSDKSharing!, didFailWithError error: Error!) { } func sharerDidCancel(_ sharer: FBSDKSharing!) { } func deleteConfirmation(postIndex: Int) { let alert = UIAlertController(title: nil, message: "Are you sure you want to delete?", preferredStyle: .actionSheet) let cancel = UIAlertAction(title: "Cancel", style: .destructive) { UIAlertAction in } let delete = UIAlertAction(title: "Delete", style: .destructive) { UIAlertAction in self.tappedIndex = postIndex self.socialfeedviewmodel.deleteSocialFeed(feedId: self.socialfeedviewmodel.getSocialFeedAt(index: postIndex).id) } alert.addAction(cancel) alert.addAction(delete) present(alert, animated: true, completion: nil) } @objc func loadMore(_ sender: TableViewCell) { newFeedsWillBeAppended = true tableView.cellForRow(at: IndexPath(row: 0, section: 4))?.isHidden = true socialfeedviewmodel.fetchSocialFeeds(isPublic: true, loadMore: true) } /* LIKE OR DISLIKE A POST WHEN TAPPPED */ @objc func toggleLike(_ sender: TableViewCell) { guard let clickedCell = sender.superview?.superview?.superview?.superview as? TableViewCell else { return } if let clickedCellIndexPath = tableView.indexPath(for: clickedCell) { tappedIndex = clickedCellIndexPath.row let tappedFeed = socialfeedviewmodel.getSocialFeedAt(index: tappedIndex!) socialfeedviewmodel.likeDislikePost(feedId: tappedFeed.id, liked: tappedFeed.liked) } } /** To determine the specific index of like button on table view */ @objc func showLikes(_ sender: TableViewCell) { guard let clickedCell = sender.superview?.superview?.superview?.superview as? TableViewCell else { return } if let clickedCellIndexPath = tableView.indexPath(for: clickedCell) { tappedIndex = clickedCellIndexPath.row let tappedFeed = socialfeedviewmodel.getSocialFeedAt(index: tappedIndex!) if tappedFeed.totalLike > 0 { guard Reachability.isConnectedToNetwork() else { self.popUpMessage(value: 15) return } self.performSegue(withIdentifier: "showLikedBy", sender: nil) } } } /** To determine the specific index of comment button on table view */ @objc func showComments(_ sender: TableViewCell) { guard let clickedCell = sender.superview?.superview?.superview?.superview as? TableViewCell else { return } if let clickedCellIndexPath = tableView.indexPath(for: clickedCell) { tappedIndex = clickedCellIndexPath.row guard Reachability.isConnectedToNetwork() else { self.popUpMessage(value: 15) return } self.performSegue(withIdentifier: "showCommentsBy", sender: nil) } } /** To display alert message for report */ func reportAlert(postIndex: Int) { let alert = UIAlertController(title:nil, message:nil, preferredStyle: .actionSheet) let feedToReport = self.socialfeedviewmodel.getSocialFeedAt(index: postIndex) let spam = UIAlertAction(title: "It’s spam", style: .default) { UIAlertAction in self.socialfeedviewmodel.reportSocialFeed(feedId: feedToReport.id, reportMessage: "This is spam") } let inappropriate = UIAlertAction(title: "It’s inappropriate", style: .default) { UIAlertAction in self.socialfeedviewmodel.reportSocialFeed(feedId: feedToReport.id, reportMessage: "This is inappropriate") } let cancel = UIAlertAction(title: "Cancel", style: .destructive) { UIAlertAction in } alert.addAction(spam) alert.addAction(inappropriate) alert.addAction(cancel) present(alert, animated: true, completion: nil) } /** To display alert message after report is send */ func reportSendAlert() { let alert = UIAlertController(title:nil, message:"Your report has been send for review.", preferredStyle: .actionSheet) let cancel = UIAlertAction(title: "OK", style: .cancel) { UIAlertAction in } alert.addAction(cancel) present(alert, animated: true, completion: nil) } /** Update available balance of user */ func setAvailableBalanceInStringAttributeFormat(label: UILabel){ var amount = "N/A" let balance = UserDefaults.standard.object(forKey: "com.gmeremit.balance") as? String if balance != "N/A" && balance != nil && balance != "" { amount = getCommaAddedAmountString(amountString: balance!) } let amountUnit = " KRW" let fontAttribute = [ NSAttributedStringKey.font: UIFont(name: "SanFranciscoDisplay-Regular", size: 18.0)! ] let amountAttribute = NSMutableAttributedString(string: amount) let amountUnitAttribute = NSMutableAttributedString(string: amountUnit,attributes: fontAttribute) amountUnitAttribute.addAttribute(NSAttributedStringKey.foregroundColor, value: UIColor(hex:0x4a4a4a), range: NSRange(location:0, length: amountUnitAttribute.length)) let balanceAttribute = NSMutableAttributedString() balanceAttribute.append(amountAttribute) balanceAttribute.append(amountUnitAttribute) label.attributedText = balanceAttribute } } /*---------------MAIN TABLE VIEW------------ -----------------HANDLES THEN NUMBER OF CELLS IN TABLEVIEW------------ -----------------HANDLES THE NUMBER OF SECTIONS IN TABLEVIEW------------ -----------------HANDLES THE SECTION HEIGHT IN TABLEVIEW------------ */ extension HomeViewController: UIScrollViewDelegate { @IBAction func scrollToTop(_ sender: Any) { tableView.scrollToRow(at: IndexPath(row:0, section: 0), at: UITableViewScrollPosition.top, animated: true) } func scrollViewDidScroll(_ scrollView: UIScrollView) { if tableView.indexPathsForVisibleRows!.contains(IndexPath(row: 0, section: 1)) && isTopMenuVisible { topMenuView.isHidden = true tableViewTopConstraint.constant = 0 isTopMenuVisible = false } if !tableView.indexPathsForVisibleRows!.contains(IndexPath(row: 0, section: 1)) && !isTopMenuVisible { setUpTopMenu() topMenuView.isHidden = false tableViewTopConstraint.constant = topMenuView.frame.height isTopMenuVisible = true } } func setUpTopMenu() { if let menuIndexArray = UserDefaults.standard.array(forKey: "com.gmeremit.collectionViewMenuIndexArray") as? [Int] { buttonMenuItem0.setImage(UIImage(named: collectionViewMenuIconArray[menuIndexArray[0]]!), for: .normal) buttonMenuItem0.tag = menuIndexArray[0] buttonMenuItem1.setImage(UIImage(named: collectionViewMenuIconArray[menuIndexArray[1]]!), for: .normal) buttonMenuItem1.tag = menuIndexArray[1] buttonMenuItem2.setImage(UIImage(named: collectionViewMenuIconArray[menuIndexArray[2]]!), for: .normal) buttonMenuItem2.tag = menuIndexArray[2] labelMenuItem0.text = collectionViewMenuNameArray[menuIndexArray[0]] labelMenuItem1.text = collectionViewMenuNameArray[menuIndexArray[1]] labelMenuItem2.text = collectionViewMenuNameArray[menuIndexArray[2]] buttonMenuItem0.addTarget(self, action: #selector(performRedirection(_:)), for: .touchUpInside) buttonMenuItem1.addTarget(self, action: #selector(performRedirection(_:)), for: .touchUpInside) buttonMenuItem2.addTarget(self, action: #selector(performRedirection(_:)), for: .touchUpInside) } } @objc func performRedirection(_ sender: UIButton) { switch sender.tag { case 0: if (UserDefaults.standard.object(forKey: "com.gmeremit.isVerified") as! Bool) { self.performSegue(withIdentifier: "recipientList", sender: nil) } else { self.popUpMessage(value: 13) } case 1: if (UserDefaults.standard.object(forKey: "com.gmeremit.isVerified") as! Bool) { self.performSegue(withIdentifier: "mobileRecharge", sender: nil) } else { self.popUpMessage(value: 13) } case 2: self.performSegue(withIdentifier: "todayRate", sender: nil) case 3: self.performSegue(withIdentifier: "trackTransfer", sender: nil) case 4: self.performSegue(withIdentifier: "transactionStatement", sender: nil) case 5: if (UserDefaults.standard.object(forKey: "com.gmeremit.isVerified") as! Bool) { self.performSegue(withIdentifier: "walletTransfer", sender: nil) } else { self.popUpMessage(value: 13) } default: return } } } extension HomeViewController: UITableViewDelegate, UITableViewDataSource { func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { guard let index = TableViewCells.init(rawValue: indexPath.section) else {return 0} switch index { case .balance: return 100 // if (UserDefaults.standard.object(forKey: "com.gmeremit.isVerified") as! Bool) { // return 136 // } else { // return 100 // } case .collection: let widthCell = ((view.frame.width - (insetForCollectionView * 3) ) - 10) / 2 let heightForCollectionViewCell = widthCell * (170 / 120) if showAllCollectionViewCells! { return heightForCollectionViewCell * 1.7 } else { return heightForCollectionViewCell * 1.151 } case .status: tableView.estimatedRowHeight = 100 return UITableViewAutomaticDimension case .social: tableView.estimatedRowHeight = 300 return UITableViewAutomaticDimension case .loadMore: tableView.estimatedRowHeight = 100 return UITableViewAutomaticDimension default: return 0 } } func numberOfSections(in tableView: UITableView) -> Int { return self.sections.count } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { guard let index = TableViewCells.init(rawValue: section) else {return 0} switch index { case .balance: return 1 case .collection: return 1 case .status: return 1 case .social: if allowFetchRequest && self.socialfeedviewmodel.getPublicSocialFeedsCount() == 0 { socialfeedviewmodel.fetchSocialFeeds(isPublic: true, loadMore: false) allowFetchRequest = false return 0 } return self.socialfeedviewmodel.getPublicSocialFeedsCount() case .loadMore: return 1 default: return 0 } } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { guard let index = TableViewCells.init(rawValue: indexPath.section) else {return UITableViewCell()} switch index { case .balance: cell = tableView.dequeueReusableCell(withIdentifier: "topCell", for: indexPath) as! TableViewCell if isVerifiedUser() { // cell.viewVerify.alpha = 0 cell.viewTop.alpha = 1 // // cell.btnLoadBalance.addTarget(self, action:#selector(loadBalanceTap(_:)), for:.touchUpInside) cell.btnRewardPoint.setTitle(UserDefaults.standard.object(forKey: "com.gmeremit.rewardPoint") as? String, for: .normal) cell.btnRewardPoint.addTarget(self, action:#selector(rewardTap(_:)), for:.touchUpInside) setAvailableBalanceInStringAttributeFormat(label: cell.labelAvailableBalance) let nickName = UserDefaults.standard.object(forKey: "com.gmeremit.nickName") as? String if nickName == nil || nickName == "" { let nameArray = (UserDefaults.standard.object(forKey: "com.gmeremit.fullName") as! String).split(separator: " ") if let firstName = nameArray.first { cell.labelUsername.text = String(firstName) } } else { cell.labelUsername.text = nickName } } else { // cell.viewTop.alpha = 0 // cell.viewVerify.alpha = 1 // todo: keep in view did load for first time dashboard entry. self.alert(message: "Your document is in verification process. Thereafter you can enjoy GME online service. Thank you for registering with us!.") cell.btnAgnet.addTarget(self, action:#selector(agentTap(_:)), for:.touchUpInside) } return cell case .collection: cell = tableView.dequeueReusableCell(withIdentifier: "collectionCell", for: indexPath) as! TableViewCell cell.collectionView.isScrollEnabled = false cell.collectionView.dataSource = self cell.collectionView.delegate = self cell.collectionView.reloadData() cell.buttonShowless?.addTarget(self, action:#selector(showLessButtonTap(_:)), for:.touchUpInside) if showAllCollectionViewCells! { cell.buttonShowless.isHidden = false } else { cell.buttonShowless.isHidden = true } cell.collectionView.addGestureRecognizer(longPressGesture) return cell case .status: cell = tableView.dequeueReusableCell(withIdentifier: "statusCell", for: indexPath) as! TableViewCell cell.labelUserNameInitialStatus.isHidden = false cell.labelUserNameInitialStatus.backgroundColor = UIColor(hex: 0x2e3192) cell.labelUserNameInitialStatus.layer.cornerRadius = cell.labelUserNameInitialStatus.frame.height / 2 cell.labelUserNameInitialStatus.text = getFirstName().prefix(1).uppercased() let userDpString = UserDefaults.standard.object(forKey: "com.gmeremit.dpUrl") as? String if let userDpUrl = URL(string: userDpString!) { cell.imageViewUserStatus.isHidden = false cell.imageViewUserStatus.sd_setImage(with: userDpUrl, placeholderImage: nil, options: [.progressiveDownload,.scaleDownLargeImages], completed: nil) cell.imageViewUserStatus.layer.cornerRadius = cell.imageViewUserStatus.frame.height/2 cell.labelUserNameInitialStatus.isHidden = true } cell.buttonUploadStatus.addTarget(self, action: #selector(uploadTextStatus(_:)), for: .touchUpInside) cell.buttonUploadImage.addTarget(self, action: #selector(uploadImageStatus(_:)), for: .touchUpInside) return cell case .social: socialfeedviewmodel.setAccessType(accessType: "public") let socialFeed = self.socialfeedviewmodel.getSocialFeedAt(index:indexPath.row) if socialFeed.feedText != nil && socialFeed.feedText != "" { if socialFeed.feedImageId != nil { //CASE 3: text and image return self.getTableViewCell(indexPath: indexPath, socialFeed: socialFeed, mode: 3) } else { //CASE 1: only text return self.getTableViewCell(indexPath: indexPath, socialFeed: socialFeed, mode: 1) } } else { //CASE 2: only image return self.getTableViewCell(indexPath: indexPath, socialFeed: socialFeed, mode: 2) } case .loadMore: cell = tableView.dequeueReusableCell(withIdentifier: "loadMoreCell", for: indexPath) as! TableViewCell if socialfeedviewmodel.loadMore() { cell.buttonLoadMore.addTarget(self, action: #selector(loadMore(_:)), for: .touchUpInside) cell.buttonLoadMore.isHidden = false } else { cell.buttonLoadMore.isHidden = true } return cell default: return cell } } } /*---------------IMAGE RELATED TASKS------------ -----------------IMAGE DIALOG------------ -----------------GALLERY AND CAMERA ACTION------------*/ extension HomeViewController { func addUserProfileImage(){ guard let tabController = self.tabBarController else { return } self.navigationController?.navigationBar.isUserInteractionEnabled = false let popUpViewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "popUpAddUserProfile") as! PopUpAddUserProfileViewController tabController.addChildViewController(popUpViewController) popUpViewController.view.frame = tabController.view.bounds tabController.view.addSubview(popUpViewController.view) popUpViewController.didMove(toParentViewController: tabController) } @objc func showUploadOptions(tapGestureRecognizer: UITapGestureRecognizer) { let alert = UIAlertController(title: "Choose Image", message: nil, preferredStyle: .actionSheet) alert.addAction(UIAlertAction(title: "Camera", style: .default, handler: { _ in self.openCamera() })) alert.addAction(UIAlertAction(title: "Gallery", style: .default, handler: { _ in self.openGallery() })) alert.addAction(UIAlertAction.init(title: "Cancel", style: .destructive, handler: nil)) self.dismiss(animated: false, completion: nil) self.present(alert, animated: true, completion: nil) } func openCamera() { if(UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.camera)) { imagePicker.sourceType = UIImagePickerControllerSourceType.camera imagePicker.allowsEditing = false present(imagePicker, animated: true, completion: nil) } else { let alert = UIAlertController(title: "Warning", message: "You don't have camera", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil)) self.present(alert, animated: true, completion: nil) } } func openGallery() { imagePicker.delegate = self imagePicker.sourceType = UIImagePickerControllerSourceType.photoLibrary imagePicker.allowsEditing = false present(imagePicker, animated: true, completion: nil) } } /*---------------NAVIGATION PICKER------------ -----------------HANDLES IMAGE PICKING------------ -----------------HANDLES PICKING FROM CAMERA AND GALLERY------------*/ extension HomeViewController: UINavigationControllerDelegate, UIImagePickerControllerDelegate { func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) { if let image = info[UIImagePickerControllerOriginalImage] as? UIImage { //imageView.image = image dismiss(animated: true, completion: nil) } } func imagePickerControllerDidCancel(_ picker: UIImagePickerController) { dismiss(animated: true, completion: nil) } } /*---------------COLLECTION VIEW------------ -----------------HANDLES COLLECTION VIEW ITEMS------------ -----------------HANDLES COLLECTION VIEW MARGINS------------ -----------------HANDLES COLLECTION VIEW ITEMS DRAG------------*/ extension HomeViewController: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return numberCellsInCollectionView! } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "transactionCell", for: indexPath) as! TransactionCollectionViewCell if numberCellsInCollectionView == 4 { cell.btnDragNdrop.isHidden = true } else { cell.btnDragNdrop.isHidden = false } cell.transactionLabel.text = collectionViewMenuNameArray[collectionViewMenuIndexArray[indexPath.row]] cell.transactionImageView.image = UIImage(named: collectionViewMenuIconArray[collectionViewMenuIndexArray[indexPath.row]]!) return cell } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { switch collectionViewMenuIndexArray[indexPath.row] { case 0: if (UserDefaults.standard.object(forKey: "com.gmeremit.isVerified") as! Bool) { // self.performSegue(withIdentifier: "recipientList", sender: nil) // RecipientListViewController // recipientList let viewcontroller = UIStoryboard.init(name: "RecipientListViewController", bundle: nil).instantiateViewController(withIdentifier: "RecipientListViewController") as! RecipientListViewController self.navigationController?.pushViewController(viewcontroller, animated: true) } else { self.popUpMessage(value: 13) } case 1: if (UserDefaults.standard.object(forKey: "com.gmeremit.isVerified") as! Bool) { self.performSegue(withIdentifier: "mobileRecharge", sender: nil) } else { self.popUpMessage(value: 13) } case 2: let exchangeRateWireFrame = ExchangeRatesWireframe() if let navigation = self.navigationController { exchangeRateWireFrame.pushMainView(in: navigation) } case 3: self.performSegue(withIdentifier: "trackTransfer", sender: nil) case 4: self.performSegue(withIdentifier: "transactionStatement", sender: nil) case 5: self.alert(message: "This feature is comming soon") return // if (UserDefaults.standard.object(forKey: "com.gmeremit.isVerified") as! Bool) { // self.performSegue(withIdentifier: "walletTransfer", sender: nil) // } else { // self.popUpMessage(value: 13) // } case 6: showAllCollectionViewCells = true numberCellsInCollectionView = 6 /* Send MORE button to the last position by switching it with the 4th item in the menu" */ collectionViewMenuIndexArray.swapAt(3, 6) tableView.reloadSections(NSIndexSet(index: 1) as IndexSet, with: .none) default: return } } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets { return UIEdgeInsetsMake(insetForCollectionView, insetForCollectionView, insetForCollectionView, insetForCollectionView) } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat { return insetForCollectionView } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat { return insetForCollectionView } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { let itemWidth = (collectionView.frame.width - insetForCollectionView * 2 - insetForCollectionView) / collectionViewItemsPerRow return CGSize(width: itemWidth, height: itemWidth * 120/170) } func collectionView(_ collectionView: UICollectionView, canMoveItemAt indexPath: IndexPath) -> Bool { if numberCellsInCollectionView! > 4 { return true } else { return false } } func collectionView(_ collectionView: UICollectionView, moveItemAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) { //collectionViewMenuIndexArray.swapAt(sourceIndexPath.row, destinationIndexPath.row) let elemetToMove = collectionViewMenuIndexArray[sourceIndexPath.row] collectionViewMenuIndexArray.remove(at: sourceIndexPath.row) collectionViewMenuIndexArray.insert(elemetToMove, at: destinationIndexPath.row) /* Save the user's swapped menu to be loaded next time the app is resumed */ UserDefaults.standard.set(collectionViewMenuIndexArray, forKey: "com.gmeremit.collectionViewMenuIndexArray") tableView.reloadSections(NSIndexSet(index: 1) as IndexSet, with: .none) } @objc func handleLongGesture(gesture: UILongPressGestureRecognizer) { if let tappedCollectionView = gesture.view as? UICollectionView { switch(gesture.state) { case .began: guard let selectedIndexPath = tappedCollectionView.indexPathForItem(at: gesture.location(in: tappedCollectionView)) else { break } tappedCollectionView.beginInteractiveMovementForItem(at: selectedIndexPath) case .changed: tappedCollectionView.updateInteractiveMovementTargetPosition(gesture.location(in: gesture.view!)) case .ended: tappedCollectionView.endInteractiveMovement() default: tappedCollectionView.cancelInteractiveMovement() } } } @objc func showLessButtonTap(_ sender: TableViewCell) { showAllCollectionViewCells = false numberCellsInCollectionView = 4 /* Bring MORE button to the 4th position by switching it with the last item in the menu" */ collectionViewMenuIndexArray.swapAt(3, 6) tableView.reloadSections(NSIndexSet(index: 1) as IndexSet, with: .none) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } override func viewDidDisappear(_ animated: Bool) { //RestApiMananger.sharedInstance.cancelExistingNetworkCalls() } }