You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1517 lines
59 KiB

6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
  1. // HomeViewController.swift
  2. // GMERemittance
  3. //
  4. // Created by Kushal on 12/11/17.
  5. // Copyright © 2017 Gobal Money Express Co. Ltd. All rights reserved.
  6. //
  7. import UIKit
  8. import Social
  9. import FacebookShare
  10. import FBSDKShareKit
  11. class HomeViewController: UIViewController, TableViewCellDelegate, FBSDKSharingDelegate {
  12. enum TableViewCells: Int {
  13. case balance = 0
  14. case collection = 1
  15. case status = 2
  16. case social = 3
  17. case loadMore = 4
  18. }
  19. private var isTopMenuVisible: Bool = false
  20. @IBOutlet weak var topMenuView: UIView!
  21. @IBOutlet weak var tableViewTopConstraint: NSLayoutConstraint!
  22. @IBOutlet weak var buttonMenuItem0: UIButton!
  23. @IBOutlet weak var buttonMenuItem1: UIButton!
  24. @IBOutlet weak var buttonMenuItem2: UIButton!
  25. @IBOutlet weak var labelMenuItem0: UILabel!
  26. @IBOutlet weak var labelMenuItem1: UILabel!
  27. @IBOutlet weak var labelMenuItem2: UILabel!
  28. private let homeviewmodel = HomeViewModel()
  29. private let socialfeedviewmodel = SocialFeedViewModel()
  30. private let profileViewModel = ProfileViewModel()
  31. private let notificationviewmodel = NotificationViewModel()
  32. var page: Int = 0
  33. var size: Int = 20
  34. var sections: [TableViewCells] = [.balance, .collection, .status, .social, .loadMore]
  35. private var activityIndicator: UIActivityIndicatorView = UIActivityIndicatorView()
  36. private let imagePicker = UIImagePickerController()
  37. var showAllCollectionViewCells: Bool?
  38. private let collectionViewItemsPerRow: CGFloat = 2
  39. private let insetForCollectionView: CGFloat = 5.0
  40. var numberCellsInCollectionView: Int?
  41. private var longPressGesture: UILongPressGestureRecognizer!
  42. private var collectionViewMenuIndexArray: [Int]!
  43. 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"]
  44. 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"]
  45. /* 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 */
  46. @IBOutlet weak var imageViewUserImage: UIImageView!
  47. @IBOutlet weak var tableView: UITableView!
  48. private var cell: TableViewCell!
  49. /*------ 0 => Text Status
  50. ------ 1 => Image Upload
  51. ------ 2 => Edit Status
  52. */
  53. private var statusUploadMode:Int? //IMAGE OR TEXT STATUS UPLOAD
  54. private var editablePostIndex: Int!
  55. private var selectedCell:Int? //SELECTED CELL
  56. private var selectedImage:UIImage? //EDIT IMAGE FOR REMOVE OR DELETE
  57. private var postStatus:String? //
  58. private var heartStatus:Bool?
  59. private var socialStatus:Bool?
  60. private var likeCount:Int?
  61. private var tappedIndex: Int?
  62. private var allowFetchRequest: Bool = true
  63. private var newFeedsWillBeAppended: Bool = false
  64. private var refreshControl: UIRefreshControl!
  65. private var arrayIndexPath = [IndexPath] ()
  66. private var showNotificationParameter: Bool = false
  67. private var editedIndex: Int!
  68. //--SETUP NAVBAR WHEN VIEW APPEARS PLUS RELOAD THE SOCIAL FEED WITH LOCAL DATA IF EXISTS
  69. override func viewWillAppear(_ animated: Bool) {
  70. editedIndex = nil
  71. // setUpAnotherLoginListener(genericviewmodel: socialfeedviewmodel)
  72. setUpAnotherLoginListener(genericviewmodel: profileViewModel)
  73. setUpNetworkListener()
  74. super.viewWillAppear(true)
  75. self.tabBarController?.tabBar.isHidden = false
  76. setNavBar()
  77. setActionBarIcons(showNotificationParameter: false)
  78. // setUpRefreshControl()
  79. bindUserStatusToUI()
  80. profileViewModel.fetchUserInfo(userId: nil)
  81. // socialfeedviewmodel.socialFeedsRxValue.value = nil
  82. //
  83. // socialfeedviewmodel.setAccessType(accessType: "public")
  84. // self.bindFeedsDataToUI()
  85. tableView.reloadSections(NSIndexSet(index: 3) as IndexSet, with: .none)
  86. if tappedIndex != nil {
  87. tableView.scrollToRow(at: IndexPath(row: tappedIndex!, section: 3), at: UITableViewScrollPosition.bottom, animated: true)
  88. }
  89. notificationBind()
  90. }
  91. override func viewWillDisappear(_ animated: Bool) {
  92. super.viewWillAppear(animated)
  93. self.navigationController?.navigationBar.topItem?.title = ""
  94. }
  95. func setUpRefreshControl() {
  96. refreshControl = UIRefreshControl()
  97. refreshControl.backgroundColor = UIColor(white: 0.98, alpha: 1.0)
  98. refreshControl.tintColor = UIColor.red
  99. refreshControl.addTarget(self, action: #selector(refresh(_:)), for: .valueChanged)
  100. tableView.addSubview(refreshControl)
  101. }
  102. @objc func refresh(_ sender: AnyObject) {
  103. newFeedsWillBeAppended = false
  104. // tableView.cellForRow(at: IndexPath(row: 0, section: 4))?.isHidden = true
  105. // socialfeedviewmodel.resetBeforeAfterFeedId()
  106. // socialfeedviewmodel.fetchSocialFeeds(isPublic: true, loadMore: false)
  107. }
  108. //--ALL NAV BAR FUNCTIONS HERE
  109. func setNavBar() {
  110. self.navigationController?.navigationBar.setBackgroundImage(UIImage(), for: .default)
  111. self.navigationController?.navigationBar.shadowImage = UIImage()
  112. self.navigationController?.navigationBar.isTranslucent = false
  113. self.tabBarController?.navigationItem.hidesBackButton = true
  114. let rightButton = UIBarButtonItem(image: UIImage(named: "ic_hamburger"), style: .plain, target: self, action: #selector(showSideMenu))
  115. self.tabBarController?.navigationItem.leftBarButtonItem = rightButton
  116. self.tabBarController?.navigationItem.leftBarButtonItem?.tintColor = UIColor.white
  117. self.tabBarController?.navigationController?.navigationBar.barTintColor = UIColor(hex:0xec1c24)
  118. let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 125, height: 30))
  119. imageView.contentMode = .scaleAspectFit
  120. let image = UIImage(named: "ic_gme_new")
  121. imageView.image = image
  122. self.tabBarController?.navigationItem.titleView = imageView
  123. }
  124. @objc func showSideMenu() {
  125. performSegue(withIdentifier: "showSideMenu", sender: nil)
  126. }
  127. func isVerifiedUser() -> Bool {
  128. return UserDefaults.standard.object(forKey: "com.gmeremit.isVerified") as! Bool
  129. }
  130. /**
  131. Update User data in view
  132. */
  133. func bindUserStatusToUI() {
  134. profileViewModel.userDataAvailable.value = nil
  135. profileViewModel.userDataAvailable.bind{ [weak self] in
  136. guard $0 != nil else {
  137. return
  138. }
  139. if $0! {
  140. let verified = UserDefaults.standard.object(forKey: "com.gmeremit.isVerified") as! Bool
  141. if !verified {
  142. let isVerified = self?.profileViewModel.isVerified()
  143. if isVerified! {
  144. UserDefaults.standard.set(isVerified, forKey: "com.gmeremit.isVerified")
  145. }
  146. }
  147. UserDefaults.standard.set(self?.profileViewModel.getAvailableBalance(), forKey: "com.gmeremit.balance")
  148. UserDefaults.standard.set(self?.profileViewModel.getRewardPoint(), forKey: "com.gmeremit.rewardPoint")
  149. UserDefaults.standard.set(self?.profileViewModel.getWalletNumber(), forKey: "com.gmeremit.walletNumber")
  150. /// TABLE RELOADED
  151. self?.tableView.reloadData()
  152. }
  153. self?.profileViewModel.userDataAvailable.value = nil
  154. }
  155. }
  156. func notificationBind(){
  157. notificationviewmodel.fetchNotification(page: self.page, size: self.size)
  158. notificationviewmodel.notificationFetch.bind{ [weak self] in
  159. guard $0 != nil else {
  160. return
  161. }
  162. guard $0! else {
  163. //self?.popUpMessageError(value: 10, message: (self?.notificationviewmodel.getErrorMessage())!)
  164. return
  165. }
  166. //Update the view
  167. self?.enableUserInteractions()
  168. if self?.activityIndicator != nil {
  169. self?.dismissActivityIndicator(activityIndicator: (self?.activityIndicator)!)
  170. }
  171. if (self?.notificationviewmodel.showNotification())!{
  172. self?.showNotificationParameter = true
  173. self?.setActionBarIcons(showNotificationParameter: true)
  174. } else {
  175. self?.showNotificationParameter = false
  176. self?.setActionBarIcons(showNotificationParameter: false)
  177. }
  178. }
  179. }
  180. func registerCMUser() {
  181. let appDelegate = UIApplication.shared.delegate as! AppDelegate
  182. appDelegate.notificationSet.bind { [unowned self] in
  183. guard $0 != nil else {
  184. return
  185. }
  186. self.homeviewmodel.cmRegistrationId(cmRegistrationId: appDelegate.cmRegistrationId!)
  187. }
  188. }
  189. /**
  190. @developer : Suraj Shrestha
  191. @date : 2018/02/12
  192. @des : Add action bar icons i.e notification and support
  193. */
  194. func setActionBarIcons(showNotificationParameter: Bool){
  195. let supportImage = UIImage(named: "ic_support")?.withRenderingMode(.alwaysOriginal)
  196. let supportButton = UIBarButtonItem(image:supportImage, style: .plain, target: self, action: #selector(showSupport))
  197. let notificationImage: UIImage!
  198. if showNotificationParameter {
  199. notificationImage = UIImage(named: "ic_notificationDot")?.withRenderingMode(.alwaysOriginal)
  200. } else {
  201. notificationImage = UIImage(named: "ic_notification")?.withRenderingMode(.alwaysOriginal)
  202. }
  203. let notificationButton = UIBarButtonItem(image: notificationImage, style: .plain, target: self, action: #selector(showNotification))
  204. self.tabBarController?.navigationItem.rightBarButtonItems=[notificationButton,supportButton]
  205. }
  206. /**
  207. @developer : Suraj Shrestha
  208. @date : 2018/02/12
  209. @des : Show support actions
  210. */
  211. @objc func showSupport() {
  212. let alert = UIAlertController(title:nil, message:"We are there to help you \n (Available time 10:00AM - 6:00PM)", preferredStyle: .actionSheet)
  213. alert.view.subviews.last?.subviews.last?.backgroundColor = UIColor.darkGray
  214. let liveChat = UIAlertAction(title: "Live Chat", style: .default) {
  215. UIAlertAction in
  216. }
  217. let contactNumber = UIAlertAction(title: "1588 6864", style: .default) {
  218. UIAlertAction in
  219. self.startCall(contactNumber: "1588 6864")
  220. }
  221. let supportEmail = UIAlertAction(title: "support@gmeremit.com", style: .default) {
  222. UIAlertAction in
  223. let storyboard = UIStoryboard.init(name: "Home", bundle: Bundle.main)
  224. if let messageViewController = storyboard.instantiateViewController(withIdentifier: "message") as? MessageComposeViewController {
  225. messageViewController.supportIndex = 0
  226. self.navigationController!.pushViewController(messageViewController, animated: true)
  227. }
  228. }
  229. liveChat.setValue(UIImage(named:"ic_live_chat")?.withRenderingMode(.alwaysOriginal),forKey:"image")
  230. contactNumber.setValue(UIImage(named:"ic_call")?.withRenderingMode(.alwaysOriginal),forKey:"image")
  231. supportEmail.setValue(UIImage(named:"ic_email")?.withRenderingMode(.alwaysOriginal),forKey:"image")
  232. // TODO: have to enable when zendesk is provided
  233. // alert.addAction(liveChat)
  234. alert.addAction(contactNumber)
  235. alert.addAction(supportEmail)
  236. alert.view.tintColor = UIColor.red
  237. alert.view.subviews.last?.subviews.last?.layer.cornerRadius = 10
  238. alert.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.cancel, handler: nil))
  239. present(alert, animated: true, completion: nil)
  240. }
  241. func startCall(contactNumber: String){
  242. if let url = URL(string: "tel://\(contactNumber.removeWhitespacesInBetween())"), UIApplication.shared.canOpenURL(url) {
  243. if #available(iOS 10, *) {
  244. UIApplication.shared.open(url)
  245. } else {
  246. UIApplication.shared.openURL(url)
  247. }
  248. }
  249. }
  250. @objc func showNotification(){
  251. performSegue(withIdentifier: "notification", sender: nil)
  252. }
  253. // func checkNetwork() {
  254. // if !Reachability.isConnectedToNetwork() {
  255. // self.popUpMessage(value: 15)
  256. // }
  257. // }
  258. func setUpNetworkListener() {
  259. // socialfeedviewmodel.internetConnection.value = nil
  260. // socialfeedviewmodel.internetConnection.bind { [unowned self] in
  261. // guard $0 != nil else {
  262. // return
  263. // }
  264. // self.enableUserInteractions()
  265. // self.popUpMessage(value: 15)
  266. // }
  267. }
  268. override func viewDidLoad() {
  269. super.viewDidLoad()
  270. setupDelegates()
  271. hideKeyboardWhenTappedAround()
  272. setUpRefreshControl()
  273. if numberCellsInCollectionView == nil {
  274. numberCellsInCollectionView = 4
  275. }
  276. if showAllCollectionViewCells == nil {
  277. showAllCollectionViewCells = false
  278. }
  279. /* Checks if the user's custom menu is available or not */
  280. if let menuArray = UserDefaults.standard.array(forKey: "com.gmeremit.collectionViewMenuIndexArray") as? [Int] {
  281. collectionViewMenuIndexArray = menuArray
  282. /* While loading the app (but not from myStoryViewController), MORE button should be shown */
  283. if numberCellsInCollectionView == 4 {
  284. if collectionViewMenuIndexArray[3] != 6 {
  285. collectionViewMenuIndexArray.swapAt(3, 6)
  286. }
  287. } else if numberCellsInCollectionView == 6 {
  288. if collectionViewMenuIndexArray[3] == 6 {
  289. collectionViewMenuIndexArray.swapAt(3, 6)
  290. }
  291. }
  292. } else {
  293. collectionViewMenuIndexArray = [0, 1, 2, 6, 4, 5, 3]
  294. UserDefaults.standard.set(collectionViewMenuIndexArray, forKey: "com.gmeremit.collectionViewMenuIndexArray")
  295. }
  296. longPressGesture = UILongPressGestureRecognizer(target: self, action: #selector(self.handleLongGesture(gesture:)))
  297. imagePicker.delegate = self
  298. tableView.tableFooterView = UIView()
  299. registerCMUser()
  300. if UserDefaults.standard.bool(forKey: "com.gmeremit.showImageAlert") {
  301. self.addUserProfileImage()
  302. }
  303. }
  304. private func setupDelegates() {
  305. tableView.delegate = self
  306. tableView.dataSource = self
  307. }
  308. override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
  309. switch segue.identifier {
  310. case "statusUpdate"?:
  311. let statusUploadViewController = segue.destination as! StatusUploadViewController
  312. statusUploadViewController.statusUploadMode = statusUploadMode
  313. statusUploadViewController.editablePostIndex = editablePostIndex
  314. statusUploadViewController.socialfeedviewmodel = socialfeedviewmodel
  315. statusUploadViewController.showNotificationParameter = showNotificationParameter
  316. case "showLikedBy"?:
  317. let likedByViewController = segue.destination as! LikesViewController
  318. likedByViewController.socialfeedviewmodel = socialfeedviewmodel
  319. likedByViewController.tappedIndex = tappedIndex
  320. case "showCommentsBy"?:
  321. let commentsViewController = segue.destination as! CommentsViewController
  322. commentsViewController.socialfeedviewmodel = socialfeedviewmodel
  323. commentsViewController.tappedIndex = tappedIndex
  324. case "myStory"?:
  325. let myStoryViewController = segue.destination as! MyStoryViewController
  326. myStoryViewController.socialfeedviewmodel = socialfeedviewmodel
  327. myStoryViewController.showNotificationParameter = showNotificationParameter
  328. case "notification"?:
  329. let notificationViewController = segue.destination as! NotificationViewController
  330. notificationViewController.socialfeedviewmodel = socialfeedviewmodel
  331. default:
  332. return
  333. }
  334. }
  335. }
  336. /*---------------ALL ACTIONS RELATED TO SOCIAL WALL HERE------------
  337. */
  338. extension HomeViewController {
  339. //UPLOAD TEXT AS STATUS
  340. @objc func uploadTextStatus(_ sender: TableViewCell) {
  341. statusUploadMode = 0
  342. self.performSegue(withIdentifier: "statusUpdate", sender: nil)
  343. }
  344. //UPLOAD IMAGE AS STATUS
  345. @objc func uploadImageStatus(_ sender: TableViewCell) {
  346. statusUploadMode = 1
  347. self.performSegue(withIdentifier: "statusUpdate", sender: nil)
  348. }
  349. //DATA BINDING
  350. func bindFeedsDataToUI() {
  351. socialfeedviewmodel.socialFeedsRxValue.bind { [weak self] in
  352. guard $0 != nil, self?.socialfeedviewmodel != nil else {
  353. return
  354. }
  355. guard $0! != 0 else {
  356. //self.popUpMessageError(value: 10, message: self.socialfeedviewmodel.getErrorMessage())
  357. self?.socialfeedviewmodel.socialFeedsRxValue.value = nil
  358. return
  359. }
  360. switch $0! {
  361. case socialWallCode.fetchPostsPublic.rawValue:
  362. let count = self?.socialfeedviewmodel.getPublicSocialFeedsCount()
  363. if count! > 0 {
  364. if (self?.newFeedsWillBeAppended)! {
  365. self?.arrayIndexPath.removeAll()
  366. self?.tableView.beginUpdates()
  367. let currentCount = self?.socialfeedviewmodel.getCurrentlyFetchedFeedCount()
  368. for i in 0...(self?.socialfeedviewmodel.getCurrentlyFetchedFeedCount())!-1 {
  369. self?.arrayIndexPath.append(IndexPath.init(row: count! - currentCount! + i, section: 3))
  370. }
  371. self?.tableView.insertRows(at: (self?.arrayIndexPath)!, with: .automatic)
  372. self?.tableView.endUpdates()
  373. self?.tableView.cellForRow(at: IndexPath(row: 0, section: 4))?.isHidden = false
  374. } else {
  375. if (self?.refreshControl.isRefreshing)! {
  376. self?.refreshControl.endRefreshing()
  377. }
  378. self?.tableView.reloadSections(NSIndexSet(index: 3) as IndexSet, with: .none)
  379. self?.tableView.reloadSections(NSIndexSet(index: 4) as IndexSet, with: .none)
  380. }
  381. }
  382. case socialWallCode.deletePost.rawValue:
  383. self?.socialfeedviewmodel.removeSocialFeed(atIndex: (self?.tappedIndex!)!)
  384. self?.tableView.deleteRows(at: [IndexPath(item: (self?.tappedIndex!)!, section: 3)], with: .automatic)
  385. case socialWallCode.likeUnlikePost.rawValue:
  386. self?.socialfeedviewmodel.updateSocialFeedArrayLikeNumber(atIndex: (self?.tappedIndex!)!)
  387. self?.tableView.reloadRows(at: [IndexPath(item: (self?.tappedIndex!)!, section: 3)], with: UITableViewRowAnimation.automatic)
  388. case socialWallCode.reportPost.rawValue:
  389. self?.reportSendAlert()
  390. case socialWallCode.createUpdatePost.rawValue:
  391. self?.dismissActivityIndicator(activityIndicator: (self?.activityIndicator)!)
  392. self?.tableView.reloadSections(IndexSet(integer: 3), with: UITableViewRowAnimation.automatic)
  393. guard let index = self?.editedIndex else {
  394. return
  395. }
  396. self?.tableView.scrollToRow(at: IndexPath(row: index, section: 3), at: UITableViewScrollPosition.none, animated: false)
  397. self?.editedIndex = nil
  398. let alert = UIAlertController(title:"", message:"This post is made private." , preferredStyle: .actionSheet)
  399. self?.present(alert, animated: true, completion: nil)
  400. let when = DispatchTime.now() + 2
  401. DispatchQueue.main.asyncAfter(deadline: when){
  402. alert.dismiss(animated: true, completion: nil)
  403. }
  404. default:
  405. return
  406. }
  407. self?.socialfeedviewmodel.socialFeedsRxValue.value = nil
  408. }
  409. }
  410. /// loadBalance
  411. @objc func loadBalanceTap(_ sender: TableViewCell) {
  412. guard let navController = self.navigationController else { return }
  413. let popUpViewController = UIStoryboard(name: "Home", bundle: nil).instantiateViewController(withIdentifier: "loadBalance") as! LoadBalanceViewController
  414. navController.addChildViewController(popUpViewController)
  415. popUpViewController.view.frame = navController.view.bounds
  416. navController.view.addSubview(popUpViewController.view)
  417. popUpViewController.didMove(toParentViewController: navController)
  418. }
  419. @objc func rewardTap(_ sender: TableViewCell) {
  420. let storyboard = UIStoryboard.init(name: "Reward", bundle: Bundle.main)
  421. let vController = storyboard.instantiateViewController(withIdentifier: "RewardViewController") as! RewardViewController
  422. self.navigationController!.pushViewController(vController, animated: true)
  423. }
  424. @objc func agentTap(_ sender: TableViewCell) {
  425. let storyboard = UIStoryboard.init(name: "Home", bundle: Bundle.main)
  426. let vController = storyboard.instantiateViewController(withIdentifier: "PayoutViewController") as! PayoutViewController
  427. self.navigationController!.pushViewController(vController, animated: true)
  428. }
  429. @IBAction func showMyStories(_ sender: Any) {
  430. self.performSegue(withIdentifier: "myStory", sender: nil)
  431. }
  432. //DISPLAY FEEDS ON THE GME WALL
  433. func getTableViewCell(indexPath: IndexPath, socialFeed : SocialFeed, mode: Int) -> UITableViewCell {
  434. let cell: TableViewCell!
  435. switch mode {
  436. case 1:
  437. cell = tableView.dequeueReusableCell(withIdentifier: "socialCellText", for: indexPath) as! TableViewCell
  438. cell.labelStatus.text = socialFeed.feedText
  439. cell.labelStatus.textColor = UIColor(red:0.29, green:0.29, blue:0.29, alpha:1.0)
  440. case 2:
  441. cell = tableView.dequeueReusableCell(withIdentifier: "socialCellImage", for: indexPath) as! TableViewCell
  442. cell.imageViewSocial.sd_setImage(with: URL(string: socialFeed.feedImage!)!, placeholderImage: nil, options: [.progressiveDownload,.scaleDownLargeImages], completed: nil)
  443. cell.postImageHeight.constant = view.frame.width
  444. case 3:
  445. cell = tableView.dequeueReusableCell(withIdentifier: "socialCellTextImage", for: indexPath) as! TableViewCell
  446. cell.labelStatus.text = socialFeed.feedText
  447. cell.labelStatus.textColor = UIColor(red:0.29, green:0.29, blue:0.29, alpha:1.0)
  448. cell.imageViewSocial.sd_setImage(with: URL(string: socialFeed.feedImage!)!, placeholderImage: nil, options: [.progressiveDownload,.scaleDownLargeImages], completed: nil)
  449. cell.postImageHeight.constant = view.frame.width
  450. default:
  451. cell = tableView.dequeueReusableCell(withIdentifier: "socialCellTextImage", for: indexPath) as! TableViewCell
  452. }
  453. cell.layer.borderColor = UIColor(red:0.91, green:0.93, blue:0.95, alpha:1.0).cgColor
  454. cell.layer.borderWidth = 2
  455. cell.imageViewUserImage.layer.cornerRadius = cell.imageViewUserImage.frame.height / 2
  456. cell.viewSocialActionConstraint.constant = 58.5
  457. cell.imageViewUserImage.layer.cornerRadius = cell.imageViewUserImage.frame.height / 2
  458. cell.editPostButton?.addTarget(self, action:#selector(showPostOptions(_:)), for:.touchUpInside)
  459. cell.heartButton?.addTarget(self, action:#selector(toggleLike(_:)), for:.touchUpInside)
  460. cell.likeButton?.addTarget(self, action:#selector(showLikes(_:)), for:.touchUpInside)
  461. cell.commentButton?.addTarget(self, action: #selector(showComments(_:)), for: .touchUpInside)
  462. //Display USERNAME who has posted the feed
  463. cell.labelSocialUsername.text = socialfeedviewmodel.getFullName(feed: socialFeed)
  464. //Display USER IMAGE
  465. cell.labelUserNameInitial.isHidden = false
  466. cell.labelUserNameInitial.backgroundColor = UIColor(hex: 0x2e3192)
  467. cell.labelUserNameInitial.layer.cornerRadius = cell.labelUserNameInitial.frame.height / 2
  468. cell.labelUserNameInitial.text = socialFeed.firstName.prefix(1).uppercased()
  469. if let userDpString = socialFeed.userDpUrl {
  470. if let userDpUrl = URL(string: userDpString) {
  471. cell.imageViewUserImage.isHidden = false
  472. cell.imageViewUserImage.sd_setImage(with: userDpUrl, placeholderImage: nil, options: [.progressiveDownload,.scaleDownLargeImages], completed: nil)
  473. }
  474. cell.labelUserNameInitial.isHidden = true
  475. }
  476. //Display timeStamp (ago date)
  477. cell.labelTimeStamp.text = socialFeed.agoDate
  478. //Display LIKE status
  479. if socialFeed.liked {
  480. cell.heartButton?.setImage(UIImage(named:"ic_heartfull"), for: UIControlState.normal)
  481. }
  482. else {
  483. cell.heartButton?.setImage(UIImage(named:"ic_heart"), for: UIControlState.normal)
  484. }
  485. //Display total number of LIKES
  486. if socialFeed.totalLike > 1 {
  487. cell.likeButton.setTitle("\(socialFeed.totalLike) Likes", for:UIControlState.normal)
  488. }
  489. else {
  490. cell.likeButton.setTitle("\(socialFeed.totalLike) Like", for:UIControlState.normal)
  491. }
  492. //Display total number of COMMENTS
  493. if socialFeed.totalComment > 1 {
  494. cell.commentButton.setTitle(" \(socialFeed.totalComment) Comments", for: UIControlState.normal)
  495. }
  496. else {
  497. cell.commentButton.setTitle(" \(socialFeed.totalComment) Comment", for: UIControlState.normal)
  498. }
  499. return cell
  500. }
  501. /**
  502. To determine the specific cell for edit the post
  503. */
  504. @objc func showPostOptions(_ sender: TableViewCell) {
  505. guard let clickedCell = sender.superview?.superview?.superview as? TableViewCell else {
  506. return
  507. }
  508. if let clickedCellIndexPath = tableView.indexPath(for: clickedCell) {
  509. enumeratePostOptions(index: clickedCellIndexPath.row)
  510. }
  511. }
  512. /**
  513. Alert message for current user
  514. */
  515. func enumeratePostOptions(index: Int) {
  516. let alert = UIAlertController(title:nil, message:nil, preferredStyle: .actionSheet)
  517. if self.socialfeedviewmodel.postBelongsToMe(postIndex: index) {
  518. let edit = UIAlertAction(title: "Edit this post", style: .default) {
  519. UIAlertAction in
  520. self.statusUploadMode = 2
  521. self.editablePostIndex = index
  522. self.performSegue(withIdentifier: "statusUpdate", sender: nil)
  523. }
  524. let delete = UIAlertAction(title: "Delete this post", style: .default) {
  525. UIAlertAction in
  526. self.deleteConfirmation(postIndex: index)
  527. }
  528. let moveToPrivate = UIAlertAction(title: "Hide this post from GME Community", style: .default) {
  529. UIAlertAction in
  530. // self.tappedIndex = index
  531. let feedToEdit = self.socialfeedviewmodel.getSocialFeedAt(index: index)
  532. if let feedText = feedToEdit.feedText {
  533. self.socialfeedviewmodel.updateFeedText(text: feedText)
  534. }
  535. if let feedImageId = feedToEdit.feedImageId {
  536. self.socialfeedviewmodel.setFeedImageId(imageId: feedImageId)
  537. }
  538. self.editedIndex = index
  539. self.showActivityIndicator(activityIndicator: self.activityIndicator)
  540. self.socialfeedviewmodel.updateSocialFeed(feed: feedToEdit, index: index, toggle: true)
  541. }
  542. let cancel = UIAlertAction(title: "Cancel", style: .destructive) {
  543. UIAlertAction in
  544. }
  545. alert.addAction(moveToPrivate)
  546. alert.addAction(edit)
  547. alert.addAction(delete)
  548. alert.addAction(cancel)
  549. } else {
  550. let report = UIAlertAction(title: "Report", style: .default) {
  551. UIAlertAction in
  552. self.reportAlert(postIndex: index)
  553. }
  554. let share = UIAlertAction(title: "Share this post", style: .default) {
  555. UIAlertAction in
  556. if self.socialfeedviewmodel.getSocialFeedAt(index: index).feedImageId == nil{
  557. self.sharePost(postIndex: index)
  558. }
  559. }
  560. let cancel = UIAlertAction(title: "Cancel", style: .destructive) {
  561. UIAlertAction in
  562. }
  563. alert.addAction(report)
  564. if self.socialfeedviewmodel.getSocialFeedAt(index: index).feedImageId == nil{
  565. alert.addAction(share)
  566. }
  567. alert.addAction(cancel)
  568. }
  569. present(alert, animated: true, completion: nil)
  570. }
  571. /**
  572. Share the status of GME app to facebook
  573. */
  574. func sharePost(postIndex: Int){
  575. let content = FBSDKShareLinkContent()
  576. content.contentURL = URL(string: "https://itunes.apple.com/us/app/gme/id1366910197?ls=1&mt=8")
  577. // content.hashtag = FBSDKHashtag(string: "#FeelingGood")
  578. if let shareText = self.socialfeedviewmodel.getSocialFeedAt(index: postIndex).feedText{
  579. content.quote = shareText
  580. }
  581. let dialog = FBSDKShareDialog()
  582. dialog.fromViewController = self
  583. dialog.shareContent = content
  584. dialog.delegate = self
  585. if !dialog.canShow() {
  586. dialog.mode = FBSDKShareDialogMode.native
  587. }
  588. dialog.show()
  589. }
  590. func sharer(_ sharer: FBSDKSharing!, didCompleteWithResults results: [AnyHashable : Any]!) {
  591. }
  592. func sharer(_ sharer: FBSDKSharing!, didFailWithError error: Error!) {
  593. }
  594. func sharerDidCancel(_ sharer: FBSDKSharing!) {
  595. }
  596. func deleteConfirmation(postIndex: Int) {
  597. let alert = UIAlertController(title: nil, message: "Are you sure you want to delete?", preferredStyle: .actionSheet)
  598. let cancel = UIAlertAction(title: "Cancel", style: .destructive) {
  599. UIAlertAction in
  600. }
  601. let delete = UIAlertAction(title: "Delete", style: .destructive) {
  602. UIAlertAction in
  603. self.tappedIndex = postIndex
  604. self.socialfeedviewmodel.deleteSocialFeed(feedId: self.socialfeedviewmodel.getSocialFeedAt(index: postIndex).id)
  605. }
  606. alert.addAction(cancel)
  607. alert.addAction(delete)
  608. present(alert, animated: true, completion: nil)
  609. }
  610. @objc func loadMore(_ sender: TableViewCell) {
  611. newFeedsWillBeAppended = true
  612. tableView.cellForRow(at: IndexPath(row: 0, section: 4))?.isHidden = true
  613. socialfeedviewmodel.fetchSocialFeeds(isPublic: true, loadMore: true)
  614. }
  615. /* LIKE OR DISLIKE A POST WHEN TAPPPED */
  616. @objc func toggleLike(_ sender: TableViewCell) {
  617. guard let clickedCell = sender.superview?.superview?.superview?.superview as? TableViewCell else {
  618. return
  619. }
  620. if let clickedCellIndexPath = tableView.indexPath(for: clickedCell) {
  621. tappedIndex = clickedCellIndexPath.row
  622. let tappedFeed = socialfeedviewmodel.getSocialFeedAt(index: tappedIndex!)
  623. socialfeedviewmodel.likeDislikePost(feedId: tappedFeed.id, liked: tappedFeed.liked)
  624. }
  625. }
  626. /**
  627. To determine the specific index of like button on table view
  628. */
  629. @objc func showLikes(_ sender: TableViewCell) {
  630. guard let clickedCell = sender.superview?.superview?.superview?.superview as? TableViewCell else {
  631. return
  632. }
  633. if let clickedCellIndexPath = tableView.indexPath(for: clickedCell) {
  634. tappedIndex = clickedCellIndexPath.row
  635. let tappedFeed = socialfeedviewmodel.getSocialFeedAt(index: tappedIndex!)
  636. if tappedFeed.totalLike > 0 {
  637. guard Reachability.isConnectedToNetwork() else {
  638. self.popUpMessage(value: 15)
  639. return
  640. }
  641. self.performSegue(withIdentifier: "showLikedBy", sender: nil)
  642. }
  643. }
  644. }
  645. /**
  646. To determine the specific index of comment button on table view
  647. */
  648. @objc func showComments(_ sender: TableViewCell) {
  649. guard let clickedCell = sender.superview?.superview?.superview?.superview as? TableViewCell else {
  650. return
  651. }
  652. if let clickedCellIndexPath = tableView.indexPath(for: clickedCell) {
  653. tappedIndex = clickedCellIndexPath.row
  654. guard Reachability.isConnectedToNetwork() else {
  655. self.popUpMessage(value: 15)
  656. return
  657. }
  658. self.performSegue(withIdentifier: "showCommentsBy", sender: nil)
  659. }
  660. }
  661. /**
  662. To display alert message for report
  663. */
  664. func reportAlert(postIndex: Int) {
  665. let alert = UIAlertController(title:nil, message:nil, preferredStyle: .actionSheet)
  666. let feedToReport = self.socialfeedviewmodel.getSocialFeedAt(index: postIndex)
  667. let spam = UIAlertAction(title: "It’s spam", style: .default) {
  668. UIAlertAction in
  669. self.socialfeedviewmodel.reportSocialFeed(feedId: feedToReport.id, reportMessage: "This is spam")
  670. }
  671. let inappropriate = UIAlertAction(title: "It’s inappropriate", style: .default) {
  672. UIAlertAction in
  673. self.socialfeedviewmodel.reportSocialFeed(feedId: feedToReport.id, reportMessage: "This is inappropriate")
  674. }
  675. let cancel = UIAlertAction(title: "Cancel", style: .destructive) {
  676. UIAlertAction in
  677. }
  678. alert.addAction(spam)
  679. alert.addAction(inappropriate)
  680. alert.addAction(cancel)
  681. present(alert, animated: true, completion: nil)
  682. }
  683. /**
  684. To display alert message after report is send
  685. */
  686. func reportSendAlert() {
  687. let alert = UIAlertController(title:nil, message:"Your report has been send for review.", preferredStyle: .actionSheet)
  688. let cancel = UIAlertAction(title: "OK", style: .cancel) {
  689. UIAlertAction in
  690. }
  691. alert.addAction(cancel)
  692. present(alert, animated: true, completion: nil)
  693. }
  694. /**
  695. Update available balance of user
  696. */
  697. func setAvailableBalanceInStringAttributeFormat(label: UILabel){
  698. var amount = "N/A"
  699. let balance = UserDefaults.standard.object(forKey: "com.gmeremit.balance") as? String
  700. if balance != "N/A" && balance != nil && balance != "" {
  701. amount = getCommaAddedAmountString(amountString: balance!)
  702. }
  703. let amountUnit = " KRW"
  704. let fontAttribute = [ NSAttributedStringKey.font: UIFont(name: "SanFranciscoDisplay-Regular", size: 18.0)! ]
  705. let amountAttribute = NSMutableAttributedString(string: amount)
  706. let amountUnitAttribute = NSMutableAttributedString(string: amountUnit,attributes: fontAttribute)
  707. amountUnitAttribute.addAttribute(NSAttributedStringKey.foregroundColor, value: UIColor(hex:0x4a4a4a), range: NSRange(location:0, length: amountUnitAttribute.length))
  708. let balanceAttribute = NSMutableAttributedString()
  709. balanceAttribute.append(amountAttribute)
  710. balanceAttribute.append(amountUnitAttribute)
  711. label.attributedText = balanceAttribute
  712. }
  713. }
  714. /*---------------MAIN TABLE VIEW------------
  715. -----------------HANDLES THEN NUMBER OF CELLS IN TABLEVIEW------------
  716. -----------------HANDLES THE NUMBER OF SECTIONS IN TABLEVIEW------------
  717. -----------------HANDLES THE SECTION HEIGHT IN TABLEVIEW------------
  718. */
  719. extension HomeViewController: UIScrollViewDelegate {
  720. @IBAction func scrollToTop(_ sender: Any) {
  721. tableView.scrollToRow(at: IndexPath(row:0, section: 0), at: UITableViewScrollPosition.top, animated: true)
  722. }
  723. func scrollViewDidScroll(_ scrollView: UIScrollView) {
  724. if tableView.indexPathsForVisibleRows!.contains(IndexPath(row: 0, section: 1)) && isTopMenuVisible {
  725. topMenuView.isHidden = true
  726. tableViewTopConstraint.constant = 0
  727. isTopMenuVisible = false
  728. }
  729. if !tableView.indexPathsForVisibleRows!.contains(IndexPath(row: 0, section: 1)) && !isTopMenuVisible {
  730. setUpTopMenu()
  731. topMenuView.isHidden = false
  732. tableViewTopConstraint.constant = topMenuView.frame.height
  733. isTopMenuVisible = true
  734. }
  735. }
  736. func setUpTopMenu() {
  737. if let menuIndexArray = UserDefaults.standard.array(forKey: "com.gmeremit.collectionViewMenuIndexArray") as? [Int] {
  738. buttonMenuItem0.setImage(UIImage(named: collectionViewMenuIconArray[menuIndexArray[0]]!), for: .normal)
  739. buttonMenuItem0.tag = menuIndexArray[0]
  740. buttonMenuItem1.setImage(UIImage(named: collectionViewMenuIconArray[menuIndexArray[1]]!), for: .normal)
  741. buttonMenuItem1.tag = menuIndexArray[1]
  742. buttonMenuItem2.setImage(UIImage(named: collectionViewMenuIconArray[menuIndexArray[2]]!), for: .normal)
  743. buttonMenuItem2.tag = menuIndexArray[2]
  744. labelMenuItem0.text = collectionViewMenuNameArray[menuIndexArray[0]]
  745. labelMenuItem1.text = collectionViewMenuNameArray[menuIndexArray[1]]
  746. labelMenuItem2.text = collectionViewMenuNameArray[menuIndexArray[2]]
  747. buttonMenuItem0.addTarget(self, action: #selector(performRedirection(_:)), for: .touchUpInside)
  748. buttonMenuItem1.addTarget(self, action: #selector(performRedirection(_:)), for: .touchUpInside)
  749. buttonMenuItem2.addTarget(self, action: #selector(performRedirection(_:)), for: .touchUpInside)
  750. }
  751. }
  752. @objc func performRedirection(_ sender: UIButton) {
  753. switch sender.tag {
  754. case 0:
  755. if (UserDefaults.standard.object(forKey: "com.gmeremit.isVerified") as! Bool) {
  756. self.performSegue(withIdentifier: "recipientList", sender: nil)
  757. } else {
  758. self.popUpMessage(value: 13)
  759. }
  760. case 1:
  761. if (UserDefaults.standard.object(forKey: "com.gmeremit.isVerified") as! Bool) {
  762. self.performSegue(withIdentifier: "mobileRecharge", sender: nil)
  763. } else {
  764. self.popUpMessage(value: 13)
  765. }
  766. case 2:
  767. self.performSegue(withIdentifier: "todayRate", sender: nil)
  768. case 3:
  769. self.performSegue(withIdentifier: "trackTransfer", sender: nil)
  770. case 4:
  771. self.performSegue(withIdentifier: "transactionStatement", sender: nil)
  772. case 5:
  773. if (UserDefaults.standard.object(forKey: "com.gmeremit.isVerified") as! Bool) {
  774. self.performSegue(withIdentifier: "walletTransfer", sender: nil)
  775. } else {
  776. self.popUpMessage(value: 13)
  777. }
  778. default:
  779. return
  780. }
  781. }
  782. }
  783. extension HomeViewController: UITableViewDelegate, UITableViewDataSource {
  784. func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
  785. guard let index = TableViewCells.init(rawValue: indexPath.section) else {return 0}
  786. switch index {
  787. case .balance:
  788. return 100
  789. // if (UserDefaults.standard.object(forKey: "com.gmeremit.isVerified") as! Bool) {
  790. // return 136
  791. // } else {
  792. // return 100
  793. // }
  794. case .collection:
  795. let widthCell = ((view.frame.width - (insetForCollectionView * 3) ) - 10) / 2
  796. let heightForCollectionViewCell = widthCell * (170 / 120)
  797. if showAllCollectionViewCells! {
  798. return heightForCollectionViewCell * 1.7
  799. } else {
  800. return heightForCollectionViewCell * 1.151
  801. }
  802. case .status:
  803. tableView.estimatedRowHeight = 100
  804. return UITableViewAutomaticDimension
  805. case .social:
  806. tableView.estimatedRowHeight = 300
  807. return UITableViewAutomaticDimension
  808. case .loadMore:
  809. tableView.estimatedRowHeight = 100
  810. return UITableViewAutomaticDimension
  811. default:
  812. return 0
  813. }
  814. }
  815. func numberOfSections(in tableView: UITableView) -> Int {
  816. return self.sections.count
  817. }
  818. func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
  819. guard let index = TableViewCells.init(rawValue: section) else {return 0}
  820. switch index {
  821. case .balance:
  822. return 1
  823. case .collection:
  824. return 1
  825. case .status:
  826. return 1
  827. case .social:
  828. if allowFetchRequest && self.socialfeedviewmodel.getPublicSocialFeedsCount() == 0 {
  829. socialfeedviewmodel.fetchSocialFeeds(isPublic: true, loadMore: false)
  830. allowFetchRequest = false
  831. return 0
  832. }
  833. return self.socialfeedviewmodel.getPublicSocialFeedsCount()
  834. case .loadMore:
  835. return 1
  836. default:
  837. return 0
  838. }
  839. }
  840. func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
  841. guard let index = TableViewCells.init(rawValue: indexPath.section) else {return UITableViewCell()}
  842. switch index {
  843. case .balance:
  844. cell = tableView.dequeueReusableCell(withIdentifier: "topCell", for: indexPath) as! TableViewCell
  845. if isVerifiedUser() {
  846. // cell.viewVerify.alpha = 0
  847. cell.viewTop.alpha = 1
  848. //
  849. // cell.btnLoadBalance.addTarget(self, action:#selector(loadBalanceTap(_:)), for:.touchUpInside)
  850. cell.btnRewardPoint.setTitle(UserDefaults.standard.object(forKey: "com.gmeremit.rewardPoint") as? String, for: .normal)
  851. cell.btnRewardPoint.addTarget(self, action:#selector(rewardTap(_:)), for:.touchUpInside)
  852. setAvailableBalanceInStringAttributeFormat(label: cell.labelAvailableBalance)
  853. let nickName = UserDefaults.standard.object(forKey: "com.gmeremit.nickName") as? String
  854. if nickName == nil || nickName == "" {
  855. let nameArray = (UserDefaults.standard.object(forKey: "com.gmeremit.fullName") as! String).split(separator: " ")
  856. if let firstName = nameArray.first {
  857. cell.labelUsername.text = String(firstName)
  858. }
  859. } else {
  860. cell.labelUsername.text = nickName
  861. }
  862. } else {
  863. // cell.viewTop.alpha = 0
  864. // cell.viewVerify.alpha = 1
  865. // todo: keep in view did load for first time dashboard entry.
  866. self.alert(message: "Your document is in verification process. Thereafter you can enjoy GME online service. Thank you for registering with us!.")
  867. cell.btnAgnet.addTarget(self, action:#selector(agentTap(_:)), for:.touchUpInside)
  868. }
  869. return cell
  870. case .collection:
  871. cell = tableView.dequeueReusableCell(withIdentifier: "collectionCell", for: indexPath) as! TableViewCell
  872. cell.collectionView.isScrollEnabled = false
  873. cell.collectionView.dataSource = self
  874. cell.collectionView.delegate = self
  875. cell.collectionView.reloadData()
  876. cell.buttonShowless?.addTarget(self, action:#selector(showLessButtonTap(_:)), for:.touchUpInside)
  877. if showAllCollectionViewCells! {
  878. cell.buttonShowless.isHidden = false
  879. } else {
  880. cell.buttonShowless.isHidden = true
  881. }
  882. cell.collectionView.addGestureRecognizer(longPressGesture)
  883. return cell
  884. case .status:
  885. cell = tableView.dequeueReusableCell(withIdentifier: "statusCell", for: indexPath) as! TableViewCell
  886. cell.labelUserNameInitialStatus.isHidden = false
  887. cell.labelUserNameInitialStatus.backgroundColor = UIColor(hex: 0x2e3192)
  888. cell.labelUserNameInitialStatus.layer.cornerRadius = cell.labelUserNameInitialStatus.frame.height / 2
  889. cell.labelUserNameInitialStatus.text = getFirstName().prefix(1).uppercased()
  890. let userDpString = UserDefaults.standard.object(forKey: "com.gmeremit.dpUrl") as? String
  891. if let userDpUrl = URL(string: userDpString!) {
  892. cell.imageViewUserStatus.isHidden = false
  893. cell.imageViewUserStatus.sd_setImage(with: userDpUrl, placeholderImage: nil, options: [.progressiveDownload,.scaleDownLargeImages], completed: nil)
  894. cell.imageViewUserStatus.layer.cornerRadius = cell.imageViewUserStatus.frame.height/2
  895. cell.labelUserNameInitialStatus.isHidden = true
  896. }
  897. cell.buttonUploadStatus.addTarget(self, action: #selector(uploadTextStatus(_:)), for: .touchUpInside)
  898. cell.buttonUploadImage.addTarget(self, action: #selector(uploadImageStatus(_:)), for: .touchUpInside)
  899. return cell
  900. case .social:
  901. socialfeedviewmodel.setAccessType(accessType: "public")
  902. let socialFeed = self.socialfeedviewmodel.getSocialFeedAt(index:indexPath.row)
  903. if socialFeed.feedText != nil && socialFeed.feedText != "" {
  904. if socialFeed.feedImageId != nil {
  905. //CASE 3: text and image
  906. return self.getTableViewCell(indexPath: indexPath, socialFeed: socialFeed, mode: 3)
  907. } else {
  908. //CASE 1: only text
  909. return self.getTableViewCell(indexPath: indexPath, socialFeed: socialFeed, mode: 1)
  910. }
  911. } else {
  912. //CASE 2: only image
  913. return self.getTableViewCell(indexPath: indexPath, socialFeed: socialFeed, mode: 2)
  914. }
  915. case .loadMore:
  916. cell = tableView.dequeueReusableCell(withIdentifier: "loadMoreCell", for: indexPath) as! TableViewCell
  917. if socialfeedviewmodel.loadMore() {
  918. cell.buttonLoadMore.addTarget(self, action: #selector(loadMore(_:)), for: .touchUpInside)
  919. cell.buttonLoadMore.isHidden = false
  920. } else {
  921. cell.buttonLoadMore.isHidden = true
  922. }
  923. return cell
  924. default:
  925. return cell
  926. }
  927. }
  928. }
  929. /*---------------IMAGE RELATED TASKS------------
  930. -----------------IMAGE DIALOG------------
  931. -----------------GALLERY AND CAMERA ACTION------------*/
  932. extension HomeViewController {
  933. func addUserProfileImage(){
  934. guard let tabController = self.tabBarController else {
  935. return
  936. }
  937. self.navigationController?.navigationBar.isUserInteractionEnabled = false
  938. let popUpViewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "popUpAddUserProfile") as! PopUpAddUserProfileViewController
  939. tabController.addChildViewController(popUpViewController)
  940. popUpViewController.view.frame = tabController.view.bounds
  941. tabController.view.addSubview(popUpViewController.view)
  942. popUpViewController.didMove(toParentViewController: tabController)
  943. }
  944. @objc func showUploadOptions(tapGestureRecognizer: UITapGestureRecognizer) {
  945. let alert = UIAlertController(title: "Choose Image", message: nil, preferredStyle: .actionSheet)
  946. alert.addAction(UIAlertAction(title: "Camera", style: .default, handler: { _ in
  947. self.openCamera()
  948. }))
  949. alert.addAction(UIAlertAction(title: "Gallery", style: .default, handler: { _ in
  950. self.openGallery()
  951. }))
  952. alert.addAction(UIAlertAction.init(title: "Cancel", style: .destructive, handler: nil))
  953. self.dismiss(animated: false, completion: nil)
  954. self.present(alert, animated: true, completion: nil)
  955. }
  956. func openCamera() {
  957. if(UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.camera)) {
  958. imagePicker.sourceType = UIImagePickerControllerSourceType.camera
  959. imagePicker.allowsEditing = false
  960. present(imagePicker, animated: true, completion: nil)
  961. }
  962. else {
  963. let alert = UIAlertController(title: "Warning", message: "You don't have camera", preferredStyle: .alert)
  964. alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
  965. self.present(alert, animated: true, completion: nil)
  966. }
  967. }
  968. func openGallery() {
  969. imagePicker.delegate = self
  970. imagePicker.sourceType = UIImagePickerControllerSourceType.photoLibrary
  971. imagePicker.allowsEditing = false
  972. present(imagePicker, animated: true, completion: nil)
  973. }
  974. }
  975. /*---------------NAVIGATION PICKER------------
  976. -----------------HANDLES IMAGE PICKING------------
  977. -----------------HANDLES PICKING FROM CAMERA AND GALLERY------------*/
  978. extension HomeViewController: UINavigationControllerDelegate, UIImagePickerControllerDelegate {
  979. func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
  980. if let image = info[UIImagePickerControllerOriginalImage] as? UIImage {
  981. //imageView.image = image
  982. dismiss(animated: true, completion: nil)
  983. }
  984. }
  985. func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
  986. dismiss(animated: true, completion: nil)
  987. }
  988. }
  989. /*---------------COLLECTION VIEW------------
  990. -----------------HANDLES COLLECTION VIEW ITEMS------------
  991. -----------------HANDLES COLLECTION VIEW MARGINS------------
  992. -----------------HANDLES COLLECTION VIEW ITEMS DRAG------------*/
  993. extension HomeViewController: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
  994. func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
  995. return numberCellsInCollectionView!
  996. }
  997. func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
  998. let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "transactionCell", for: indexPath) as! TransactionCollectionViewCell
  999. if numberCellsInCollectionView == 4 {
  1000. cell.btnDragNdrop.isHidden = true
  1001. } else {
  1002. cell.btnDragNdrop.isHidden = false
  1003. }
  1004. cell.transactionLabel.text = collectionViewMenuNameArray[collectionViewMenuIndexArray[indexPath.row]]
  1005. cell.transactionImageView.image = UIImage(named: collectionViewMenuIconArray[collectionViewMenuIndexArray[indexPath.row]]!)
  1006. return cell
  1007. }
  1008. func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
  1009. switch collectionViewMenuIndexArray[indexPath.row] {
  1010. case 0:
  1011. if (UserDefaults.standard.object(forKey: "com.gmeremit.isVerified") as! Bool) {
  1012. // self.performSegue(withIdentifier: "recipientList", sender: nil)
  1013. // RecipientListViewController
  1014. // recipientList
  1015. let viewcontroller = UIStoryboard.init(name: "RecipientListViewController", bundle: nil).instantiateViewController(withIdentifier: "RecipientListViewController") as! RecipientListViewController
  1016. self.navigationController?.pushViewController(viewcontroller, animated: true)
  1017. } else {
  1018. self.popUpMessage(value: 13)
  1019. }
  1020. case 1:
  1021. if (UserDefaults.standard.object(forKey: "com.gmeremit.isVerified") as! Bool) {
  1022. self.performSegue(withIdentifier: "mobileRecharge", sender: nil)
  1023. } else {
  1024. self.popUpMessage(value: 13)
  1025. }
  1026. case 2:
  1027. let exchangeRateWireFrame = ExchangeRatesWireframe()
  1028. if let navigation = self.navigationController {
  1029. exchangeRateWireFrame.pushMainView(in: navigation)
  1030. }
  1031. case 3:
  1032. self.performSegue(withIdentifier: "trackTransfer", sender: nil)
  1033. case 4:
  1034. self.performSegue(withIdentifier: "transactionStatement", sender: nil)
  1035. case 5:
  1036. self.alert(message: "This feature is comming soon")
  1037. return
  1038. // if (UserDefaults.standard.object(forKey: "com.gmeremit.isVerified") as! Bool) {
  1039. // self.performSegue(withIdentifier: "walletTransfer", sender: nil)
  1040. // } else {
  1041. // self.popUpMessage(value: 13)
  1042. // }
  1043. case 6:
  1044. showAllCollectionViewCells = true
  1045. numberCellsInCollectionView = 6
  1046. /* Send MORE button to the last position by switching it with the 4th item in the menu" */
  1047. collectionViewMenuIndexArray.swapAt(3, 6)
  1048. tableView.reloadSections(NSIndexSet(index: 1) as IndexSet, with: .none)
  1049. default:
  1050. return
  1051. }
  1052. }
  1053. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
  1054. return UIEdgeInsetsMake(insetForCollectionView, insetForCollectionView, insetForCollectionView, insetForCollectionView)
  1055. }
  1056. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
  1057. return insetForCollectionView
  1058. }
  1059. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
  1060. return insetForCollectionView
  1061. }
  1062. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
  1063. let itemWidth = (collectionView.frame.width - insetForCollectionView * 2 - insetForCollectionView) / collectionViewItemsPerRow
  1064. return CGSize(width: itemWidth, height: itemWidth * 120/170)
  1065. }
  1066. func collectionView(_ collectionView: UICollectionView, canMoveItemAt indexPath: IndexPath) -> Bool {
  1067. if numberCellsInCollectionView! > 4 {
  1068. return true
  1069. } else {
  1070. return false
  1071. }
  1072. }
  1073. func collectionView(_ collectionView: UICollectionView, moveItemAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
  1074. //collectionViewMenuIndexArray.swapAt(sourceIndexPath.row, destinationIndexPath.row)
  1075. let elemetToMove = collectionViewMenuIndexArray[sourceIndexPath.row]
  1076. collectionViewMenuIndexArray.remove(at: sourceIndexPath.row)
  1077. collectionViewMenuIndexArray.insert(elemetToMove, at: destinationIndexPath.row)
  1078. /* Save the user's swapped menu to be loaded next time the app is resumed */
  1079. UserDefaults.standard.set(collectionViewMenuIndexArray, forKey: "com.gmeremit.collectionViewMenuIndexArray")
  1080. tableView.reloadSections(NSIndexSet(index: 1) as IndexSet, with: .none)
  1081. }
  1082. @objc func handleLongGesture(gesture: UILongPressGestureRecognizer) {
  1083. if let tappedCollectionView = gesture.view as? UICollectionView {
  1084. switch(gesture.state) {
  1085. case .began:
  1086. guard let selectedIndexPath = tappedCollectionView.indexPathForItem(at: gesture.location(in: tappedCollectionView)) else {
  1087. break
  1088. }
  1089. tappedCollectionView.beginInteractiveMovementForItem(at: selectedIndexPath)
  1090. case .changed:
  1091. tappedCollectionView.updateInteractiveMovementTargetPosition(gesture.location(in: gesture.view!))
  1092. case .ended:
  1093. tappedCollectionView.endInteractiveMovement()
  1094. default:
  1095. tappedCollectionView.cancelInteractiveMovement()
  1096. }
  1097. }
  1098. }
  1099. @objc func showLessButtonTap(_ sender: TableViewCell) {
  1100. showAllCollectionViewCells = false
  1101. numberCellsInCollectionView = 4
  1102. /* Bring MORE button to the 4th position by switching it with the last item in the menu" */
  1103. collectionViewMenuIndexArray.swapAt(3, 6)
  1104. tableView.reloadSections(NSIndexSet(index: 1) as IndexSet, with: .none)
  1105. }
  1106. override func didReceiveMemoryWarning() {
  1107. super.didReceiveMemoryWarning()
  1108. }
  1109. override func viewDidDisappear(_ animated: Bool) {
  1110. //RestApiMananger.sharedInstance.cancelExistingNetworkCalls()
  1111. }
  1112. }